在java中使用int a = a + 1和++之间是否有任何性能差异?如果是这样哪个更好,为什么? [英] Is there any performance difference between using int a=a+1 and a++ in java? If so which is better and why?

查看:209
本文介绍了在java中使用int a = a + 1和++之间是否有任何性能差异?如果是这样哪个更好,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能简单解释一下我理解这个吗?

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 classname

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和++之间是否有任何性能差异?如果是这样哪个更好,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆