c++vector

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


Which method is faster and has less overhead?

Method 1:

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

Method 2:

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

You may say that the example is meaningless! But this is just a snippet from my big code. In short I want to know is it better to

"create a vector once and clear it for usage"

or

"create a new vector every time"

UPDATE

Thanks for the suggestions, I tested both and here are the results

Method 1:

 $ time ./test1

 real    0m0.044s
 user    0m0.042s
 sys     0m0.002s

Method 2:

$ time ./test2

real    0m0.601s
user    0m0.599s
sys     0m0.002s

Clearing the vector is better. Maybe this help someone else :)


Solution

  • 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 your compiler optimizer might do with this code.