Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

c++ - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...