问题描述
查看生成的字节码:
@H_301_3@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; }
产生(使用@H_301_3@javap -c classname)
@H_301_3@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):
@H_301_3@x = x + 1
创造
@H_301_3@12: iload_1 13: iconst_1 14: iadd 15: istore_1
而
@H_301_3@y++; ++z; a += 1;
全部导致
@H_301_3@iinc
但是,在笔记本电脑上进行粗略的性能测试后,两者的运行时间几乎没有差异(有时++ x更快,有时x = x + 1更快),因此我不必担心性能影响。
解决方法
使用int a=a+1
和a++
in 之间有什么性能差异Java
?
如果是这样,哪个更好,为什么?您能简要解释一下以了解这一点吗?