Follow up: resize + assign is often faster than reserve + emplace_back for vector

published at 05.03.2026 15:34 by Jens Weller
Save to Instapaper Pocket

Last week I've posted about some test code to explore the question if resize + assign is faster than reserve + emplace_back.

And in the initial setup there is not such a big difference, using clang 17 + GCCs standard lib - the current default config of quick-bench.

But if you switch to GCC (13.2) on quick-bench, then the result becomes different: resize + assign is now always faster. 1.9 times faster when using size_t:

blog/gcc_assign_size_t.png

And 1.6 times faster when using the struct with 4 size_t:

blog/gcc_assign_struct.png

At least when looking at the case where only this is measured. If the vector grows with the task, size_t still is faster with resize + assign, but only by 1.5 faster:

blog/gcc_grow_assign_size_t.png

For the struct with 4 size_t this gets back to being equal:

blog/gcc_grow_assign_struct.png

So, with GCC resize + assign is a valid strategy. reserve + emplace_back does not get the needed optimizations to compete. Link to quick-bench.

For clang + libc++(LLVM) it gets kinda in the same range. In the non growing example the struct with 4 size_t is 1.5 times faster with resize + assign. The size_t only is with 2.1 times faster the best result. When letting the vector grow during the test, and hence at some point no reallocation is needed, the numbers are similar to GCC too: no difference for the struct and size_t only is 1.4 times faster.

Its a nice result, and might give your code a nice boost in speed. As quick-bench does not offer newer versions of GCC or Clang I can't say if this gets to be different with newer versions improving for emplace_back. Its interesting to see that in the growing vector tests the smaller data type still gets the benefit. So if you do fill vectors en block in your code, you might have an opportunity to test for speed.

Join the Meeting C++ patreon community!
This and other posts on Meeting C++ are enabled by my supporters on patreon!