Why switch is faster than if

user831722 picture user831722 · Jul 15, 2011 · Viewed 80.5k times · Source

Lots of Java books describe the switch statement as being faster than the if else statement. But I did not find out anywhere why switch is faster than if.

Example

I have a situation I have to choose any one item out of two. I can use either use

switch (item) {
    case BREAD:
        //eat Bread
        break;
    default:
        //leave the restaurant
}

or

if (item == BREAD) {
    //eat Bread
} else {
    //leave the restaurant
}

considering item and BREAD is a constant int value.

In the above example which is faster in action and why?

Answer

Daniel picture Daniel · Jul 15, 2011

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.