Java 14 中扩展的 switch 表达式,除了程序员/审阅者的视觉清晰度之外,对 switch 表达式的需求还不清楚。是吗
- 与旧的 switch 表达式不同的字节码实现?
- 在执行方面比以前的版本有任何性能改进吗?
参考:https ://www.techgeeknext.com/java/java14-features
JDK 14 版本:
int numLetters = switch (day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case THURSDAY, SATURDAY -> 8;
case WEDNESDAY -> 9;
};
JDK 14 字节代码
0: iconst_1
1: istore_1
2: iload_1
3: tableswitch { // 1 to 7
1: 44
2: 44
3: 44
4: 49
5: 54
6: 54
7: 59
default: 64
}
44: bipush 6
46: goto 65
49: bipush 7
51: goto 65
54: bipush 8
56: goto 65
59: bipush 9
61: goto 65
64: iconst_0
65: istore_2
66: return
JDK - 10 代码
int numLetters;
int day = 1;
switch (day) {
case 1:
case 2:
case 3:
numLetters = 6;
break;
case 4:
numLetters = 7;
break;
case 5:
case 6:
numLetters = 8;
break;
case 7:
numLetters = 9;
break;
default:
numLetters = 0;
}
JDK - 10 字节代码
0: iconst_1
1: istore_2
2: iload_2
3: tableswitch { // 1 to 7
1: 44
2: 44
3: 44
4: 50
5: 56
6: 56
7: 62
default: 68
}
44: bipush 6
46: istore_1
47: goto 70
50: bipush 7
52: istore_1
53: goto 70
56: bipush 8
58: istore_1
59: goto 70
62: bipush 9
64: istore_1
65: goto 70
68: iconst_0
69: istore_1
70: return
除了块内的局部分配减少了 JIT 指令外,原语没有重大区别。