问题描述
std::vector<double> C(4);
for(int i = 0; i < 1000;++i)
for(int j = 0; j < 2000; ++j)
{
C[0] = 1.0;
C[1] = 1.0;
C[2] = 1.0;
C[3] = 1.0;
}
比
for(int i = 0; i < 1000;++i)
for(int j = 0; j < 2000; ++j)
{
std::vector<double> C(4);
C[0] = 1.0;
C[1] = 1.0;
C[2] = 1.0;
C[3] = 1.0;
}
我发现这是因为 std :: vector
在循环中被重复创建和实例化,但我的印象是,这将被优化掉。
I realize this happens because std::vector
is repeatedly being created and instantiated in the loop, but I was under the impression this would be optimized away.
是否完全错误,以尽可能将变量保持在循环中局部?我是在(可能是假的)印象,这将为编译器提供优化的机会。
Is it completely wrong to keep variables local in a loop whenever possible? I was under the (perhaps false) impression that this would provide optimization opportunities for the compiler.
或者也许只适用于POD类型,而不是 std :: vector
。
Or maybe that only applies to POD types and not something like std::vector
.
EDIT:我使用了完全优化的VC ++ 2005(发布模式)( / Ox
)on Windows XP
I used VC++2005 (release mode) with full optimization (/Ox
) on Windows XP
推荐答案
不,这是一个好的经验法则。但这只是一个经验法则。
最小化变量的范围为编译器提供了更多的用于寄存器分配和其他优化的自由,并且至少同样重要的是,它通常产生更可读的代码。但它也取决于重复的创造/销毁是便宜的,或被完全优化。
No, that's a good rule of thumb. But it is only a rule of thumb.Minimizing the scope of a variable gives the compiler more freedom for register allocation and other optimizations, and at least as importantly, it generally yields more readable code. But it also depends on repeated creation/destruction being cheap, or being optimized away entirely. That is often the case... But not always.
因为你已经发现,有时候这是一个坏主意。
So as you've discovered, sometimes it's a bad idea.
这篇关于在循环中创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!