jdk11-jvm-自增++
结论
java语言层面而言,前++和后++的性能及开销没有区别
java代码
class Demo{
public void pre00(){
int num=0;
++num;
}
public void post00(){
int num=0;
num++;
}
public void pre01(int num){
++num;
}
public void post01(int num){
num++;
}
public int pre02(){
int num=0;
return ++num;
}
public int post02(){
int num=0;
return num++;
}
public int pre03(int num){
return ++num;
}
public int post03(int num){
return num++;
}
}
反编译字节码
Compiled from "Demo.java"
class Demo {
Demo();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
LineNumberTable:
line 1: 0
public void pre00();
Code:
0: iconst_0 // 0入栈
1: istore_1 // 栈顶元素0放到局部变量表脚标1
2: iinc 1, 1 // 局部变量表脚标1元素自增1
5: return
LineNumberTable:
line 4: 0
line 5: 2
line 6: 5
public void post00();
Code:
0: iconst_0 // 0入栈
1: istore_1 // 栈顶元素0放到局部变量表脚标1
2: iinc 1, 1 // 局部变量表脚标1元素自增1
5: return
LineNumberTable:
line 9: 0
line 10: 2
line 11: 5
public void pre01(int);
Code:
0: iinc 1, 1 // 局部变量脚标1元素自增1 也就是方法形参num
3: return
LineNumberTable:
line 14: 0
line 15: 3
public void post01(int);
Code:
0: iinc 1, 1 // 局部变量脚标1元素自增1 也就是方法形参num
3: return
LineNumberTable:
line 18: 0
line 19: 3
public int pre02();
Code:
0: iconst_0 // 0入栈
1: istore_1 // 栈顶元素放到局部变量表脚标1处
2: iinc 1, 1 // 局部变量表脚标1处元素自增1
5: iload_1 // 将局部变量表脚标1处元素放到栈顶
6: ireturn // 栈顶元素返回
LineNumberTable:
line 22: 0
line 23: 2
public int post02();
Code:
0: iconst_0 // 0入栈
1: istore_1 // 栈顶元素放到局部变量表脚标1处
2: iload_1 // 将局部变量表脚标1处元素放到栈顶
3: iinc 1, 1 // 局部变量表脚标1处元素自增1
6: ireturn // 栈顶元素返回
LineNumberTable:
line 27: 0
line 28: 2
public int pre03(int);
Code:
0: iinc 1, 1 // 局部变量表脚标1处元素自增1
3: iload_1 // 将局部变量表脚标1处元素放到栈顶
4: ireturn // 栈顶元素返回
LineNumberTable:
line 32: 0
public int post03(int);
Code:
0: iload_1 // 将局部变量表脚标1处元素放到栈顶
1: iinc 1, 1 // 局部变量表脚标1处元素自增1
4: ireturn // 栈顶元素返回
LineNumberTable:
line 36: 0
}
图示


浙公网安备 33010602011771号