Why switch is faster than if

Posted by  Derek Honeybun
 1119  View(s)
Rate this:
I have found lots of books in java saying switch statement is faster than if else statement. But I didnot find antwhere saying why switch is faster than if.

I have a situation i have to choose any one item out of two i can use either of the following way

case BREAD:
     //eat Bread
    //leave the restaurant
or using if statement like the following

if(item== BREAD){
//eat Bread
//leave the restaurant
considering item and BREAD is constant int value

In the above example which is faster in action and why?
  1. Re: Why switch is faster than if

    Because there are special bytecodes that allow efficient switch statement evaluation when there are a lot of cases.

    If implemented with IF-statements you would have a check, a jump to the next clause, a check, a jump to the next clause and so on. With switch the JVM loads the value to compare and iterates through the value table to find a match, which is faster in most cases