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 :)
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With