Possible Duplicate:
What is the relative performance difference of if/else versus switch statement in Java?
Given the following two methods:
public static int useSwitch(int i) {
switch (i) {
case 0:
return 1;
default:
return 0;
}
}
public static int useIf(int i) {
if (i == 0)
return 1;
return 0;
}
testing shows that the switch executes marginally faster (1.4 nanoseconds per call on my machine) than the if version.
I had always believed that the benefit of a switch didn’t kick in until at least a few ifs could be avoided,
Why is switch faster than a single if?
By checking the bytecode the result is as expected:
SWITCH
IF
Now I don’t see any particular reason for which one should be slower than the other (not by a significative amount in any case). This is surely something that is related to the specific JVM implementation and how it executes these opcodes. According to common knowledge the
TABLESWITCHinstruction should be slower unless there are enough cases that makes its construction valuable but this is just common thinking. Every JVM could implement it differently so this is just speculation.Are you sure to profiled everything in a consistent way? (by giving time to JVM to warm up, by keeping just results within a confidence range and all the other things that make profiling enough correct to be used)