Which method is faster and has less overhead?
Method 1:
void foo() {
std::vector< int > aVector;
for ( int i = 0; i < 1000000; ++i ) {
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.