Why switch on String compiles into two switches

前端 未结 1 1172
独厮守ぢ
独厮守ぢ 2020-12-15 05:31

I read JVM specification on compiling switches and became interested in how switch statement on String is compiled. Here is the test method I examined (JDK1.7.0_40):

相关标签:
1条回答
  • 2020-12-15 05:59

    The cite from the javac source code:

             * The general approach used is to translate a single
             * string switch statement into a series of two chained
             * switch statements: the first a synthesized statement
             * switching on the argument string's hash value and
             * computing a string's position in the list of original
             * case labels, if any, followed by a second switch on the
             * computed integer value.  The second switch has the same
             * code structure as the original string switch statement
             * except that the string case labels are replaced with
             * positional integer constants starting at 0.
             *
             * The first switch statement can be thought of as an
             * inlined map from strings to their position in the case
             * label list.  An alternate implementation would use an
             * actual Map for this purpose, as done for enum switches.
             *
             * With some additional effort, it would be possible to
             * use a single switch statement on the hash code of the
             * argument, but care would need to be taken to preserve
             * the proper control flow in the presence of hash
             * collisions and other complications, such as
             * fallthroughs.  Switch statements with one or two
             * alternatives could also be specially translated into
             * if-then statements to omit the computation of the hash
             * code.
    
    0 讨论(0)
提交回复
热议问题