Does switch case order affect speed? [duplicate]
Solution 1:
Reordering a switch statement does not have any effect.
Looking at the Java bytecode spec, a switch
can either be compiled to a lookupswitch
or a tableswitch
instruction, switching on an int
. A lookupswitch
is always compiled with the possible values in sorted order, so reordering the constants in the code will never matter, and a tableswitch
just has an array of the possible jumps relative to a specified offset, so it, too, never cares about the original order.
See http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.lookupswitch and http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.tableswitch for details.