Creating an object in the loop

后端 未结 7 547
夕颜
夕颜 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:16

    Creation of the vector is expensive, in this case, because it may allocate an array of size 4 on the heap.

    If you know the size of the 'local' vector upfront, you may as well use an automatic array:

    for( int i = 0; i != 2000; ++i ) {
       int C[4]; // no initialization
       C[0] = 1;
       // ...
    }
    

    This way you loose the cost of allocating free memory.

提交回复
热议问题