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; }
much faster
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 understand that this is happening because std::vector repeatedly created and created in a loop, but I was impressed that it would be optimized.
Is it completely wrong to support variables locally in a loop when possible? I was under the (possibly false) impression that this would provide optimization opportunities for the compiler.
Or maybe this only applies to POD types, not std::vector .
EDIT: I used VC ++ 2005 (release mode) with full optimization ( /Ox ) in Windows XP
c ++ optimization
Jacob
source share