Search code examples
javaperformancejvmjit

Java switch smart enough to rearrange?


Given a hot piece of code that has switch with many case options (and all are with breaks e.g. can be rearranged) will JVM figure out the frequent entries to check them ahead of others?


Solution

  • Frequency or likelihood of execution of individual cases doesn't come into it. The compiler will generate either:

    • a tableswitch instruction with an associated jump table that is indexed directly by the switch value, or
    • a lookupswitch instruction with a table of key/target pairs that can (typically) be binary-searched.

    See the JVM Specification #3.10.