Search code examples
c++vectorloopsmemory-managementmemory-optimization

Clean vector every loop iteration. What is the most memory efficient way?


I have a question about the std::vector.

I have a very memory intensive algorithm where I forsee that predicting vector sizes and reserving enough memory for the vectors in advance will help me a lot with reducing memory usage.

Which of the following is better:

for ( ... ) {
  std::vector<Type> my_vector;
  my_vector.reserve(stuff_count);
  // Do stuff , and append stuff to my_vector.
}

Or this:

std::vector my_vector;
for ( ... ) {
  my_vector.clear();
  my_vector.reserve(stuff_count);
  // Do stuff , and append stuff to my_vector.
}

Please tell me which is best, or if there is an even better way of doing stuff.

Thank you very much in advance!


Solution

  • With the first variant you reallocate the vector's buffer on each iteration – that's usually quite costly. With the second variant you only reallocate occasionally. The second variant is better since speed is a priority for you.

    It's unclear from you question where the number of elements is know from. Maybe you even can quickly calculate the maximum number of elements for all iterations, set this to be the buffer size and have no reallocation.