WHY SWITCH IS FASTER THAN IF

Derek Honeybun

Total Post:17

Points:119
Posted by  Derek Honeybun
Java 
 567  View(s)
Ratings:
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.

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

switch(item){
case BREAD:
     //eat Bread
break;
default:
    //leave the restaurant
}
or using if statement like the following

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

In the above example which is faster in action and why?
  1. Mayank Tripathi

    Post:397

    Points:3117
    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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!