Pieter-Paul Kramer
Pieter-Paul Kramer

Reputation: 198

Can the C++ compiler introduce vector.reserve calls?

Occasionally I see code like

std::vector x;
x.reserve(y.size());
for (auto a : y) {
  ...
  x.push_back(...);
}

But I don't like writing reserve because it's extra clutter and feels like a micro-optimization, especially when I know y.size() will be small.

That makes me wonder: does the compiler introduce such reserve calls if they're not present in the code? It'd have to treat std::vector specially, sure, but approximately everyone uses it so that wouldn't be so bad. Are there any rules that'd prohibit the compiler from doing this?

Update: I meant specifically: in this case it's obvious that x will have y.size elements -- could/do compilers reserve that up-front?

Update 2: Rewrote body of for-loop in examples to avoid suggestions like std::transform. This is a made-up example to illustrate a case where a compiler can predict the final size of a std::vector. I don't care particularly for this specific example.

Upvotes: 2

Views: 312

Answers (1)

eerorika
eerorika

Reputation: 238471

Can the C++ compiler introduce vector.reserve calls?

It won't.

it's extra clutter

You need to weigh the cost of one line of "clutter" versus the benefits.

and feels like a micro-optimization.

Good. It is a micro-optimisation.


If y is a random access container or range, then you don't need to reserve if you use an iterator or range algorithm instead of a bare loop. For example:

auto t = std::ranges::transform_view(y, Process);
x.assign(std::begin(t), std::end(t));

If y is not a random access container / range, then using reserve is still beneficial.

Upvotes: 4

Related Questions