Question Details

No question body available.

Tags

c++

Answers (4)

Accepted Answer Available
Accepted Answer
April 8, 2026 Score: 8 Rep: 45,105 Quality: Expert Completeness: 60%

Although it looks like @candiedorange got some data that didn't really apply here, I think he had a good idea: collect some hard data and see how much difference reserving space really makes.

So, let's write a little bit of code to see how much difference calling reserve makes, for a number of sizes of vectors:

#include 
#include 
#include 
#include 
#include 

std::vector prep(std::size
t size) { std::vector ret;

for (int i=0; i
April 8, 2026 Score: 6 Rep: 12,554 Quality: Medium Completeness: 40%

A large proportion of the time, you should do neither, because the reason you know what to reserve is because you have something that models std::sized_range supplying the elements (or a way to generate them).

In that case, you should initialise the vector directly from the input range.

auto vec = source | std::views::transform(generator) | // optional std::ranges::to();
April 8, 2026 Score: 3 Rep: 222,066 Quality: Medium Completeness: 20%

Suppose you're unsure whether calling reserve() will result in a measurable performance improvement. Should you still use it, or would that be considered premature optimization?

If you are unsure and you have a use case where extra performance can seriously be expected to be useful, invest your time to measure the runnig time first. Then try it out, with and without out 'reserve'.

If you just use 'reserve' and it turns out it does not improve anything, or the extra performance is totally unimportant for any of your program's users, you only make your code more complicated without any benefit.

In reality, I only found 'reserve' useful in certain high speed calculation programs, usually in some artificial programming contests, but rarely in standard application programming.

April 8, 2026 Score: -4 Rep: 120,096 Quality: Medium Completeness: 80%

Measurable? Yes. Significant? Ehh.

I'm presuming you mean, "When the size of the resulting vector is known beforehand, should you call myvec.reserve() or pass the size in the constructor?"

The answer to that question can be found here.

And, if you turn on compiler optimization, the difference looks like this:

enter image description here

The third option is just don't tell what the final size is. How well that works depends on exactly how well the final size matches the assumed size. While that may work out for you, it's kind a rude to the poor dev who comes after you.

My rule of thumb is, if I can predict the final size then somehow I find a way to express that. Mostly because the next poor coder might not realize the final size is predictable and may actually have a reason to care, even if I can't find one today.