11 ms·
for (auto [s, n]: my_map) copies all the data needlessly, better to use for (const auto& [s, n]: my_map)
by jcelerier 3y ago
for (auto [s, n]: my_map)
copies all the data needlessly, better to use
for (const auto& [s, n]: my_map)
- heywhatupboys 3y agowhat a language
- lionkor 3y agojust consider const reference to be the default for non-primitive types
- a_e_k 3y agoMy rule of thumb is to use const references when the sizeof the type is larger than the sizeof a pointer or reference.
- repsilat 3y agoMight be worth using values/copies even a bit bigger, so long as it's "simple" data. This[1] short post argues for passing `std::string_view` (~2 pointers) by value, for - Omitting pointer indirections (loads), - Not forcing the pointee to have an address (i.e. gotta be in memory, not just registers), and - Eliminating aliasing questions, potentially leading to better codegen if the function isn't inlined. 1: https://quuxplusone.github.io/blog/2021/11/09/pass-string-view-by-value/ https://quuxplusone.github.io/blog/2021/11/09/pass-string-vi...
- nuancebydefault 3y agoThat's why some newer languages have 'const are the default'.
- Tommstein 3y agoI'm pretty sure it's the reference that makes the data not be copied.
- nuancebydefault 3y agoCopying the data to a const makes little sense in this case. The extra & choice that has emerged makes things more complicated than needed. The sad faith of this old language.
- nly 3y agoWithout the const the key would still be const.