jdk1.7 String switch的实现
?
对于int的switch,jvm是用tableswitch和lookupswitch来实现的,jdk1.7 switch增加了对string的支持,那么底层是如何实现的呢?是否增加了新的指令或是否给某些指令增加了新的含义?
?
?
看这样一个程序:
?
public static void main(java.lang.String[]); Code: 0: ldc #2 // String buzzards 2: astore_1 3: iconst_0 4: istore_2 5: aload_1 6: astore_3 7: iconst_m1 8: istore 4 10: aload_3 11: invokevirtual #3 // Method java/lang/String.hashCode:()I 14: lookupswitch { // 1 -931102253: 32 default: 59 } 32: aload_3 33: ldc #4 // String righto 35: invokevirtual #5 // Method java/lang/String.equals:(Ljava/lang/Object;) 38: ifeq 47 41: iconst_1 42: istore 4 44: goto 59 47: aload_3 48: ldc #2 // String buzzards 50: invokevirtual #5 // Method java/lang/String.equals:(Ljava/lang/Object;) 53: ifeq 59 56: iconst_0 57: istore 4 59: iload 4 61: lookupswitch { // 2 0: 88 1: 93 default: 98 } 88: iconst_1 89: istore_2 90: goto 101 93: iconst_2 94: istore_2 95: goto 101 98: bipush 6 100: istore_2 101: getstatic #6 // Field java/lang/System.out:Ljava/io/PrintStream; 104: iload_2 105: invokevirtual #7 // Method java/io/PrintStream.println:(I)V 108: return??
?
这里我们看到两个字符串都跳到32行,首先跟"righto"比较,如果不相等则跳到47行比较buzzards。
?
?
1 楼 wupuyuan 2011-08-31 多谢LZ来分享,我也仔细分析了下,觉得switch String 不如传统的if else来的效率高。当然在if时要判断更准确一些。欢迎去我空间看看 2 楼 NeverGiveUpToChange 2012-04-10 hao hao hao hao hao