在Java中使用int a = a + 1和a ++之间的性能差异 [英] Performance difference between using int a=a+1 and a++ in Java
本文介绍了在Java中使用int a = a + 1和a ++之间的性能差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Java
中使用 int a = a + 1
和 a ++
之间是否有性能差异?
Is there any performance difference between using int a=a+1
and a++
in Java
?
如果这样,哪个更好,为什么?您能简要解释一下我理解这一点吗?
If so which is better and why? Could you briefly explain me to understand this?
推荐答案
查看生成的字节码:
public static void main(String[] args) {
int x = 1;
int y = 1;
int z = 1;
int a = 1;
int b = 1;
x = x + 1;
y++;
++z;
a += 1;
b += 2;
}
生成(使用 javap -c类名
)
0: iconst_1
1: istore_1
2: iconst_1
3: istore_2
4: iconst_1
5: istore_3
6: iconst_1
7: istore 4
9: iconst_1
10: istore 5
12: iload_1
13: iconst_1
14: iadd
15: istore_1
16: iinc 2, 1
19: iinc 3, 1
22: iinc 4, 1
25: iinc 5, 2
28: return
因此使用(jdk1.6.0_18):
So using (jdk1.6.0_18):
x = x + 1
创建
12: iload_1
13: iconst_1
14: iadd
15: istore_1
而
y++;
++z;
a += 1;
所有结果
iinc
但是,在笔记本电脑上进行粗略的性能测试后,两者的运行时间几乎没有差异(有时++ x更快,有时x = x + 1更快),所以我不必担心性能影响.
However, doing a rough performance test on my laptop resulted in next to no difference in the runtime between the two (sometimes ++x was quicker, sometimes x=x+1 was quicker), so I wouldn't worry about the performance implications.
这篇关于在Java中使用int a = a + 1和a ++之间的性能差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文