logoalt Hacker News

im3w1ltoday at 2:41 PM1 replyview on HN

So one thing I thought of when reading this is that very often it is known ahead of time (at runtime or even compile-time) how many push_backs will be done. The programmer could make a reserve call but doesn't bother since the efficiency gain is minimal.

The gain is minimal for doing this optimization at one location. But doing it everywhere, that could matter. Pushing back in a loop could maybe be optimized to a single allocation and a memcopy.


Replies

tialaramextoday at 2:59 PM

In C++ programmers are often taught not to use their reservation API for this purpose because it's designed in such a way that if you don't have perfect foresight you can destroy amortization and thus get much worse performance.

For example Bjarne Stroustrup suggests you should use reservation for "avoiding invalidation of iterators" instead.

show 2 replies