Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I was reading Stroustrup's "The C++ Programming Language", where he says that out of two ways to add something to a variable

x = x + a; 

and

x += a; 

He prefers += because it is most likely better implemented. I think he means that it works faster too.
But does it really? If it depends on the compiler and other things, how do I check?

like image 784
Chiffa Avatar asked Sep 18 '12 14:09

Chiffa


People also ask

Which operations are faster?

D. Explanation: combinational circuits are often faster than sequential circuits. since, the combinational circuits do not require memory elements whereas the sequential circuits need memory devices to perform their operations in sequence. latches and flip-flops come under sequential circuits.

Is X ++ faster than x += 1?

++, += or x + 1? The bottom line is that in most but not all languages the compiler is going to make them identical anyway, so there's no difference in efficiency.


1 Answers

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 +=.

like image 55
zwol Avatar answered Sep 21 '22 22:09

zwol