Creating an object in the loop

后端 未结 7 543
夕颜
夕颜 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:04

    The second way is allocating new memory (in your case 1000*2000 times). Each one being a completely new memory location in heap (although not always new, can be in the same location). Memory allocation takes longer time than just modifying the values contained in already allocated memory.

    The first way is allocating 1 memory location array, and just modifying the values in it. If compilers do optimize for this (which isn't always the case), better not leave it to the compiler, if you can choose to allocate less memory (or less often) yourself as a programmer.

提交回复
热议问题