Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 621
Nailer Avatar asked Mar 06 '09 09:03

Nailer


People also ask

Does vector clear release memory?

clear() don't release or reallocate allocated memory, they just resize vector to zero size, leaving capacity same.

Is vector in continuous memory?

The standard does in fact guarantee that a vector is continuous in memory and that &a[0] can be passed to a C function that expects an array.

Does delete [] work on vectors?

Yes. For each time a new[] expression is executed, there must be exactly one delete[] . If there is no delete[] , then there is a leak.


3 Answers

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.

like image 140
sharptooth Avatar answered Oct 22 '22 13:10

sharptooth


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

Try and act like an engineer not a fortune teller. Create a test, and measure the difference.

like image 21
Pete Kirkham Avatar answered Oct 22 '22 14:10

Pete Kirkham


The second one could be slightly faster, but I find the first one cleaner.

like image 41
Maurice Perry Avatar answered Oct 22 '22 14:10

Maurice Perry