Why switch is faster than if

Viewed 91898

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?

5 Answers
Related