clearing a vector or defining a new vector, which one is faster

后端 未结 2 1751
一向
一向 2021-02-05 10:26

Which method is faster and has less overhead?

Method 1:

void foo() {
  std::vector< int > aVector;
  for ( int i = 0; i < 1000000; ++i ) {
              


        
2条回答
  •  盖世英雄少女心
    2021-02-05 10:56

    The clear() is most likely to be faster, as you will retain the memory that has been allocated for previous push_back()s into the vector, thus decreasing the need for allocation.

    Also you do away with 1 constructor call and 1 destructor call per loop.

    This is all ignoring what you're compiler optimizer might do with this code.

提交回复
热议问题