I had a situation where I got worse performance in push_back
-based solution compared to one using the [] operator on a resized vector. The cause of the difference was the overhead in checking whether the vector needs to expand its capacity every time it was doing a push_back
.
What made it even worse was that the compiler decided it couldn't inline the call to push_back
, but it did inline the reserve-logic into the push_back
method. This gave the overhead of a function call and the function invoked was unnecessary large. Even after some force_inline massage, it wasn't as fast as the loop based on the [] operator.
A loop based on iterators or the [] operator won't do anything but writing the value, at least not when working with simple types. If working with more advanced types, the cost of the default constructor when resizing the vector may ruin the potential wins.
Anyway, if your program spends most of its time in these kinds of loop I definitely think you should benchmark the different solutions and see if there are any performance to gain by using one of the solutions. If you are not spending considerable amount of your execution time in the function you described, you shouldn't care about this post :)