Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

vector

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 :)

like image 672
mahmood Avatar asked Oct 04 '13 19:10

mahmood


People also ask

What happens when you clear a vector?

clear() removes all the elements from a vector container, thus making its size 0. All the elements of the vector are removed using clear() function.

Which is faster set or vector?

Vector is faster for insertion and deletion of elements at the end of the container. Set is faster for insertion and deletion of elements at the middle of the container.

Do you need to clear a vector?

If you have a vector and it goes out of scope, all objects in the vector are destroyed. There isn't really a need to call clear() unless you want to dump the contents and reuse the vector.

Can you clear an empty vector?

C++ Vector Library - clear() Function The C++ function std::vector::clear() destroys the vector by removing all elements from the vector and sets size of vector to zero.


1 Answers

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.

like image 79
goji Avatar answered Sep 24 '22 00:09

goji