Creating an object in the loop

后端 未结 7 630
夕颜
夕颜 2021-01-14 00:56
 std::vector 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.         


        
7条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-14 01:09

    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.

提交回复
热议问题