The difference in performance between a + = b and a = a + b

I know that the two statements below give the same results:

a+=b; a=a+b; 

In the case a += b , a is evaluated only once, and in the case a = a + b , a is evaluated twice.

Is there a performance difference between the two? If not, are there any changes above, where is the difference?

+7
c
source share
2 answers

From the standard (section 6.5.16.2, clause 3):

A compound assignment of the form E1 op = E2 differs from a simple assignment expression * E1 = E1 > op (E2) only in the sense that the lvalue E1 is evaluated only once.

That is, if instead you do

 *a += 1 

it will only locate the target once, not twice. For "simple" variables, as in your example, this may not greatly affect. Of course, if the compiler knows that there is no need to do this twice, it can still optimize and do it once. If there are other objects that can change the pointer (for example, another thread), there is a real difference.

EDIT: Perhaps the best example is something weird, like the following (abuse of & b == & a-1 in my case):

 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 
+4
source share

a+=1 is probably the best way to go (however, the difference in performance is almost negligible). You should look for other parts of your code if you are trying to improve performance.

+1
source share

All Articles