是x + = a比x = x + a快吗? [英] Is x += a quicker than x = x + a?
问题描述
我正在阅读Stroustrup的C ++编程语言,他说,
有两种方法可以为变量添加一些东西
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;
和
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?
推荐答案
任何有价值的编译器都会为任何内置类型生成完全相同的机器语言序列code> int , float
,等等),只要语句真的是简单的 x = x + a;
并启用优化。 (值得注意的是,GCC的 -O0
是默认模式,执行反优化,例如将完全不必要的存储插入内存,确保调试器总是可以找到变量值。)
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.)
如果语句更复杂,它们可能不同。假设 f
是返回指针的函数,则
If the statement is more complicated, though, they might be different. Suppose f
is a function that returns a pointer, then
*f() += a;
只调用 f
p>
calls f
only once, whereas
*f() = *f() + a;
调用它两次。如果 f
有副作用,其中一个将是错误的(可能是后者)。即使 f
没有副作用,编译器可能无法消除第二个调用,因此后者确实可能会更慢。
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.
因为我们在这里谈论C ++,对于重载 operator +
和 operator + =
。如果 x
是这样的类型,则 - 在优化之前 - x + = a
转换为
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);
而 x = x + a
auto TEMP(x.operator+(a));
x.operator=(TEMP);
现在,如果类正确写入了和足够的,两个都会生成相同的机器语言,但它不是一个确定的事情,它是内置类型。这可能是Stroustrup在鼓励使用 + =
时所考虑的。
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 +=
.
这篇关于是x + = a比x = x + a快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!