Is x += a quicker than x = x + a?

Any compiler worth its salt will generate exactly the same machine-language sequence for both constructs for any built-in type (int, float, etc) as long as the statement really is as simple as x = x + a; and optimization is enabled. (Notably, GCC's -O0, which is the default mode, performs anti-optimizations, such as inserting completely unnecessary stores to memory, in order to ensure that debuggers can always find variable values.)

If the statement is more complicated, though, they might be different. Suppose f is a function that returns a pointer, then

*f() += a;

calls f only once, whereas

*f() = *f() + a;

calls it twice. If f has side effects, one of the two will be wrong (probably the latter). Even if f doesn't have side effects, the compiler may not be able to eliminate the second call, so the latter may indeed be slower.

And since we're talking about C++ here, the situation is entirely different for class types that overload operator+ and operator+=. If x is such a type, then -- before optimization -- x += a translates to

x.operator+=(a);

whereas x = x + a translates to

auto TEMP(x.operator+(a));
x.operator=(TEMP);

Now, if the class is properly written and the compiler's optimizer is good enough, both will wind up generating the same machine language, but it's not a sure thing like it is for built-in types. This is probably what Stroustrup is thinking of when he encourages use of +=.


You can check by looking at the dissasembly, which will be the same.

For basic types, both are equally fast.

This is output generated by a debug build (i.e. no optimizations):

    a += x;
010813BC  mov         eax,dword ptr [a]  
010813BF  add         eax,dword ptr [x]  
010813C2  mov         dword ptr [a],eax  
    a = a + x;
010813C5  mov         eax,dword ptr [a]  
010813C8  add         eax,dword ptr [x]  
010813CB  mov         dword ptr [a],eax  

For user-defined types, where you can overload operator + and operator +=, it depends on their respective implementations.


Yes! It's quicker to write, quicker to read, and quicker to figure out, for the latter in the case that x might have side effects. So it's overall quicker for the humans. The human time in general costs much more than the computer time, so that must be what you were asking about. Right?