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 sin…
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.
A deep dive into SmallVector:push_back
11–12 of 12 posts
Re: A deep dive into SmallVector:push_back
#12Earlier quoted context omitted.
API should have reserve_at_least(n) and reserve_exactly(n), instead of one reserve(n), which works as reserve_exactly(n), but described as reserve_at_least(n).
I agree that this is the better design. Rust calls these Vec::reserve and Vec::reserve_exact Zig calls the analagous methods ensureTotalCapacity and ensureTotalCapacityPrecise It's worth mentioning that talk of "exact" and "precise" may be misleading because it probably makes sense to (and despite that word exact Vec does explicitly say it might) discern that the actual allocation was big enough for slightly more ite…
A problem with just directly exposing such is it makes precise sanitizing impossible, as you'd have to tolerate some out-of-intended-bounds reads/writes. (and making the sanitizer always give exact-size allocations would also be bad as that'd end up not testing code paths that may break when they're not)