Creating an object in the loop

Posted by Jacob on Stack Overflow See other posts from Stack Overflow or by Jacob
Published on 2010-06-09T20:05:42Z Indexed on 2010/06/09 20:12 UTC
Read the original article Hit count: 208

Filed under:
|
 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.

EDIT: I use VC++2005 (release mode) with full optimization (/Ox)

© Stack Overflow or respective owner

Related posts about c++

Related posts about optimization