The extended switch expression in Java 14, the need of switch expression is unclear other than visual clarity for programmer/reviewer. Is it
- a different byte code implementation than older switch expression?
- any performance improvement in terms of execution over previous version?
Reference: https://www.techgeeknext.com/java/java14-features
JDK 14 version:
int numLetters = switch (day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case THURSDAY, SATURDAY -> 8;
case WEDNESDAY -> 9;
};
JDK 14 -byte code
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 Code
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 Byte code
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
There are no major difference for primitives, apart from local assignments within blocks has reduced JIT instructions.