public static void main(String[] a) {
String target="abc";
String r;
switch(target){
case "abc":
r="cba";
break;
default:
case "def":
r="fed";
}
System.out.println(r);
}
Eclipse JDT
Stack: 2, Locals: 4
0 ldc <String "abc"> [16]
2 astore_1 [target]
3 aload_1 [target]
4 dup
5 astore_3
6 invokevirtual java.lang.String.hashCode() : int [18]
9 lookupswitch default: 66
case 96354: 36
case 99333: 48
36 aload_3
37 ldc <String "abc"> [16]
39 invokevirtual java.lang.String.equals(java.lang.Object) : boolean [24]
42 ifne 60
45 goto 66
48 aload_3
49 ldc <String "def"> [28]
51 invokevirtual java.lang.String.equals(java.lang.Object) : boolean [24]
54 ifne 66
57 goto 66
60 ldc <String "cba"> [30]
62 astore_2 [r]
63 goto 69
66 ldc <String "fed"> [32]
68 astore_2 [r]
69 getstatic java.lang.System.out : java.io.PrintStream [34]
72 aload_2 [r]
73 invokevirtual java.io.PrintStream.println(java.lang.String) : void [40]
76 return
经过:
1.switch通过hashcode找出大概位置(因为有hashcode冲撞的可能)
2.调用String.equals方法找到正确目标字节码位置,直接执行操作
JDK7u10
stack=2, locals=5, args_size=1
0: ldc #2 // String abc
2: astore_1
3: aload_1
4: astore_3
5: iconst_m1
6: istore 4
8: aload_3
9: invokevirtual #3 // Method java/lang/String.hashCode:()I
12: lookupswitch { // 2
96354: 40
99333: 55
default: 67
}
40: aload_3
41: ldc #2 // String abc
43: invokevirtual #4 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
46: ifeq 67
49: iconst_0
50: istore 4
52: goto 67
55: aload_3
56: ldc #5 // String def
58: invokevirtual #4 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
61: ifeq 67
64: iconst_2
65: istore 4
67: iload 4
69: lookupswitch { // 2
0: 96
2: 102
default: 102
}
96: ldc #6 // String cba
98: astore_2
99: goto 105
102: ldc #7 // String fed
104: astore_2
105: getstatic #8 // Field java/lang/System.out:Ljava/io/PrintStream;
108: aload_2
109: invokevirtual #9 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
112: return
经过:
1.switch通过hashcode找出大概位置(因为有hashcode冲撞的可能)
2.调用String.equals方法找到正确目标,此目标已经在内部生成字节码时用int值代替
3.通过switch代替的int值,找到正确目标字节码位置,直接执行操作
总结:
Eclipse JDT对switch字符串生成的字节码更高效,更紧凑