How does Java's switch work under the hood?

前端 未结 7 1197
花落未央
花落未央 2020-12-10 23:54

How does Java\'s switch statement work under the hood? How does it compare the value of the variable being used, to those given in the case parts? Does it use ==

7条回答
  •  一整个雨季
    2020-12-11 00:25

    Copied from here

    In bytecode there are two forms of switch: tableswitch and lookupswitch. One assumes a dense set of keys, the other sparse. See the description of compiling switch in the JVM spec. For enums, the ordinal is found and then the code continues as the int case. I am not entirely sure how the proposed switch on String little feature in JDK7 will be implemented.

    However, heavily used code is typically compiled in any sensible JVM. The optimiser is not entirely stupid. Don't worry about it, and follow the usual heuristics for optimisation.

    You will find detailed answer over here

提交回复
热议问题