Home > DeveloperSection > Forums > Why switch is faster than if
Derek Honeybun
Derek Honeybun

Total Post:17

Posted on    December-04-2015 12:01 AM

 Java Java 

 1 Reply(s)
 283  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?

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    December-04-2015 12:07 AM

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

Don't want to miss updates? Please click the below button!

Follow MindStick