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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With