4 ms·
Vector reallocations result in an average of one* move (which yes, is effectively a copy for types like string_view) per element under normal operation. If you'
by vitus 4y ago
Vector reallocations result in an average of one* move (which yes, is effectively a copy for types like string_view) per element under normal operation. If you're concerned about that single copy (primarily: if profiling has demonstrated that this is a real bottleneck), and you know the target size a priori, then yes, by all means, use reserve.
Just be warned that if you do it wrong, you can literally make your program exponentially slower. And, that it's less imperative to do so now than it was 15 years ago.
(I'm personally much less concerned about the cost of copying 16B from a string_view, than I am about copying 24B + arbitrary amounts of underlying storage from a string.)
* Yes, I know, elements at the beginning of the vector will be moved/copied more often than elements at the end.
- jeffbee 4y ago> arbitrary amounts of underlying storage from a string The whole point of move construction is that moving a string is almost as cheap as moving a string_view. The moved-to string now owns the external storage and the moved-from string does not.
- vitus 4y agoExactly, which is why I haven't worried about it ever since I started working with C++11. It was certainly the case that reserve was critical back in the C++03 days, though.