What would be a better way (performance) to iterate primitive type container with ranged for (for reading elements values) - read elements by ref or by value?
std::vector<int> v;
for (const auto e : v) { std::cout << e; }
or
for (const auto& e : v) { std::cout << e; }
There is: Is it counter-productive to pass primitive types by reference?
Wondering if these 2 things (passing and iterating by ref and value) might be somehow related.
Another note: I do recognize what is the difference between access by ref, const-ref and value as well as copying values - I only interested in what way would perform better for READ-ONLY.
For small, primitive types, if you don't want to modify the elements of the container, then it's really a matter of style, although for such 'read-only' access, you're probably safer using the by-value approach (which will actually prevent any unintended modification of the 'originals' - although a
const
qualifier on the reference will also prevent that).However, if you do want to modify the contained elements, then you will need to iterate using a reference variable, as shown in the below code sample: