Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it more efficient to set the size of a vector up front?

Tags:

c++

stl

vector

If you are able to, is it more efficient to set the size of a vector up front? I intend to push_back values.

like image 693
pingu Avatar asked Dec 01 '22 06:12

pingu


1 Answers

Yes, it's generally a little more efficient. Don't expect a huge improvement, but at worst it's harmless (obviously assuming you only reserve the space you actually need).

For a rather unusual situation, it may improve both the time taken and the amount of space consumed. When you use push_back it'l increase the size by some multiplicative factor when you run out of space, but if you use reserve, it may allocate exactly the amount you need instead of rounding up to the next multiple of whatever factor it uses.

like image 57
Jerry Coffin Avatar answered Feb 15 '23 10:02

Jerry Coffin