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?
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 asx = 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
fis a function that returns a pointer, thencalls
fonly once, whereascalls it twice. If
fhas side effects, one of the two will be wrong (probably the latter). Even iffdoesn’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+andoperator+=. Ifxis such a type, then — before optimization —x += atranslates towhereas
x = x + atranslates toNow, 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
+=.