在Java 14中新增了扩展的switch表达式,除了提高程序员/代码审查者的视觉清晰度外,对于switch表达式的需求不是很明确。以下是需要解答的问题:
- 它与旧版本的switch表达式相比是否是一种不同的字节码实现?
- 在执行方面是否有性能改进?
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指令外,没有什么主要区别。
day = 1
的值时,没有主要的性能改进。我已经执行了循环“20亿+次”。执行时间如下:JDK-14 - 3317.8微秒和JDK 10 - 3343.200微秒。 - Jatish