As you can see from this answer, Java switch
(at least pre-1.7) does not always compile into ==
or .equals()
. Instead, it uses table lookup. While this is a very small micro-optimization, when doing a great many comparisons, table lookup will almost always be faster.
Note that this is only used for switch
statements that check against dense keys. For example, checking an enum value for all of its possibilities would probably yield this primary implementation (internally called tableswitch
).
If checking against more sparsely-populated sets of keys, the JVM will use an alternative system, known as lookupswitch
. It will instead simply compare various keys and values, doing essentially an optimized ==
comparison for each possibility. To illustrate these two methods, consider the following two switch statements:
switch (value1) {
case 0:
a();
break;
case 1:
b();
break;
case 2:
c();
break;
case 3:
d();
break;
}
switch (value2) {
case 0:
a();
break;
case 35:
b();
break;
case 103:
c();
break;
case 1001:
d();
break;
}
The first example would most likely use table lookup, while the other would (basically) use ==
comparison.