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;
}
is much faster than
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;
}
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.
Or maybe that only applies to POD types and not something like std::vector
.
EDIT: I used VC++2005 (release mode) with full optimization (/Ox
) on Windows XP