简体   繁体   English

a + = b和a = a + b之间的性能差异

[英]Performance difference between a+=b and a=a+b

I know the two statements below give the same results: 我知道下面的两个陈述给出了相同的结果:

a+=b; 
a=a+b;

In the case of a += b , a is evaluated only once while in the case of a = a + b , a is evaluated twice. 在的情况下a += ba而在的情况下,只计算一次a = a + ba被评估两次。

Is there any difference in performance between the two? 两者之间的表现有什么不同? If not, are there any variations of the above where there is a difference? 如果没有,上述哪些区别有变化?

From the standard (section 6.5.16.2, point 3): 从标准(第6.5.16.2节,第3点):

A compound assignment of the form E1 op = E2 differs from the simple assignment expression *E1 = E1 op (E2) only in that the lvalue E1 is evaluated only once. E1 op = E2形式的复合赋值与简单赋值表达式* E1 = E1 op (E2)的不同之处仅在于左值E1仅被评估一次。

That is, if instead you are doing 也就是说,如果你正在做的话

*a += 1

it will only determine the target location once instead of twice. 它只会确定目标位置一次而不是两次。 For "simple" variables as in your example, it might not make much of a difference. 对于像您的示例中的“简单”变量,它可能没有多大区别。 Of course, if the compiler knows there is no need to do it twice, it can still optimise and do it once. 当然,如果编译器知道不需要两次,它仍然可以优化并执行一次。 In case there are other entities that can change the pointer (such as another thread), there is a real difference. 如果有其他实体可以更改指针(例如另一个线程),则存在真正的差异。

EDIT: Perhaps a better example is something weird like the following (abusing the fact that &b == &a-1 in my case): 编辑:也许一个更好的例子是像下面这样奇怪的东西(滥用&b ==&a-1在我的情况下):

int a, b, *p;

a = 1; b = 5; p = &a;
*p += (--p == &b) ? 1 : 0;
printf("%d %d\n",a,b); // prints 1 6, because --p happens first, then *p

a = 1; b = 5; p = &a;
*p = *p + ((--p == &b) ? 1 : 0);
printf("%d %d\n",a,b); // prints 1 2, because the second *p is evaluated first,
                       // then --p and then the first *p

a+=1 is probably the best way to go (However the difference in performance is almost insignificant). a+=1可能是最好的方法(但性能上的差异几乎无关紧要)。 You should look up for other parts of your code if you are trying to achieve some performance improvements. 如果要尝试实现某些性能改进,则应该查找代码的其他部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM