Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preallocation and vector

Tags:

c++

vector

In c++, for vector, why preallocation is so important even if vector alocates space dynamically


1 Answers

First, it's unlikely to be "so important" for 99% of cases.

It's basically an optimization. Since vector doesn't have any idea how many elements you are going to add to it, it assumes a small default, and will have to grow if you try to add a new element and there is not enough space for a new element to be added. The grow operation can be costly as it may require allocating an entirely new buffer, copying the current contents of the vector to the new buffer, and deallocating the old buffer. By preallocating enough space, if you know how many elements you are going to add, you can avoid unnecessary growth.

Like any performance optimization, you shouldn't worry about it unless it's a bottleneck. Moreover, if you have no idea how many elements you're going to add, let the vector decide. Don't assume your randomly chosen number is going to work better than the implementation default.

like image 195
mmx Avatar answered Jan 28 '26 16:01

mmx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!