JVM字节码分析--switch语法糖
一、switch 底层实现
编译器使用 tableswitch 和 lookupswitch 两个指令来生成 switch 语句的编译代码:
int chooseNear(int i) {
switch (i) {
case 0: return 0;
case 1: return 1;
case 4: return 4;
default: return -1;
}
}
字节码如下:
0: iload_1
1: tableswitch {
// 100 to 104
0: 36
1: 38
2: 42
3: 42
4: 40
default: 42
}
可见在1到4之间字节码填充了虚假的 2、3 方便 tableswitch 通过计算偏移量即可一次找到对应的case 。比如case为1时,只需计算1 - 0 = 1即可得到偏移量为1,从 tableswitch 中取出下标为 1 的case 即可,此时算法复杂度为O(1)。
但 tableswitch 只适用于case值紧凑的情况,若case值相差太大,JVM 则自动使用 lookupswitch 指令生成编译代码:
int chooseFar(