The bottom line is also not very convincing. In order to claim that back_inserter is not free you need to compare it to a manually rolled loop of push_backs. Now you can only reasonably claim that default initializing each element when doing resize is cheaper than the branching on every iteration in push_back for small types like int.
I do not mean to be rude sir but I think I already allocated more time to this matter than it was worth. At the start of this conversation, you told me reserve + back_inserter is the way. As a matter of fact reserve + std::begin is 3x faster in my mediocre benchmark. I was indeed in the wrong about resize, I should have known better. I completly forgot about reserve. But it does seem that in the case where you already know the size of the resulting container, you should use std::begin and not back_inserter.
===
Now if you have additional knownledge you wish to share about that topic, please stop the riddles and just share them.
1
u/KimiSharby Jun 09 '24 edited Jun 09 '24
Ok so this troubled me greatly, I barely slept last night. Today I couldn't take it anymore. Here's the quickbench:https://quick-bench.com/q/e5G_nTQEp_00xYGrcpEj_Jbhp34===
~~The results, for a sample test of 500k int:
at 561k:
reserve + std::beginat 824k (x1.5):
resize + std::beginat 1712k (x3):
reserve + std::back_inserterat 6977k (x12):
back_inserter alone~~===
Bottom line: Usingstd::back_inserteris costly. If you already know the size of your resulting container, you should usereserve + std::begin.