In one of the previous articles
we’ve looked at the problems with using initializer lists for constructing std::vector. But surely there must be a better way to initialize the list, right? What if we steal an idea from Rust and use an approach similar to Rust’s vec! macro
Instead of using initializer list, we directly create a vector, reserve storage for all items in advance and push them back one by one. Looks like a recipe for success?
Unfortunately, even a quick glance at the huge assembly listing is sufficient to ruin our hopes - there is way too much copying and extra overhead involved.
Benchmark results confirmed my fears
with “macro”-like vec version being almost 2X slower.
This doesn’t mean that this approach should never be used, but it highlights the importance of designing efficient APIs, since it’s hard to overcome their deficiencies after the fact. It’s also possible to implement vec so that instead of resize and push_backs it uses vector constructor that takes a size and directly populates vector using parameter pack indices, e..g something like make_integer_sequence, but that’s a topic for another post. I’d also love to hear your thoughts, so please share them in the comments!
What I really miss is vec with_capacity