Possible Duplicates:
is “else if” faster than “switch() case” ?
What is the relative performance of if/else vs. switch in Java?
Ive been coding-in-the-run again….when the debugger steps through a case statement it jumps to the item that matches the conditions immediately, however when the same logic is specified using if/else it steps through every if statement until it finds the winner. Is the case statement more efficient, or is my debugger just optimizing the step through? (don’t worry about the syntax/errors, i typed this in SO, don’t know if it will compile, its the principle i’m after, I didn’t want to do them as ints cause i vaguely remember something about case using an offset with ints) I use C#, but im interested in a general answer across programming languages.
switch(myObject.GetType()){
case typeof(Car):
//do something
break;
case typeof(Bike):
//do something
break;
case typeof(Unicycle):
//do something
break;
case default:
break;
}
VS
Type myType = myObject.GetType();
if (myType == typeof(Car)){
//do something
}
else if (myType == typeof(Bike)){
//do something
}
else if (myType == typeof(Unicycle)){
//do something
}
else{
}
It seems that the compiler is better in optimizing a switch-statement than an if-statement.
The compiler doesn’t know if the order of evaluating the if-statements is important to you, and can’t perform any optimizations there. You could be calling methods in the if-statements, influencing variables. With the switch-statement it knows that all clauses can be evaluated at the same time and can put them in whatever order is most efficient.
Here’s a small comparison:
http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx