brc-dd
brc-dd

Reputation: 12954

Performance difference between various specifiers in range_declaration of range-based for loop

I have seen many types of type specifiers used while declaring range for a range-based for-loop like:

#include <iostream>
#include <vector>
 
int main() {
    std::vector<int> v = {0, 1, 2, 3, 4, 5};
 
    for (const int& i : v) // access by const reference
        std::cout << i << ' ';
    std::cout << '\n';
 
    for (auto i : v) // access by value, the type of i is int
        std::cout << i << ' ';
    std::cout << '\n';
 
    for (auto&& i : v) // access by forwarding reference, the type of i is int&
        std::cout << i << ' ';
    std::cout << '\n';
 
    const auto& cv = v;
 
    for (auto&& i : cv) // access by f-d reference, the type of i is const int&
        std::cout << i << ' ';
    std::cout << '\n';
}

// some aren't mentioned here, I just copied this snippet from cppreference

Which of these is expected to perform faster (after -O2 or -O3 optimisation)? Does the choice depends on the data type of vector, or on the operation(s) we're performing inside the loop.

PS: cout inside the loops is just for demo.

Upvotes: 1

Views: 63

Answers (1)

John Zwinck
John Zwinck

Reputation: 249123

None of them is expected to perform faster or slower. You have to measure to find out on your specific platform. Or read the assembly code, which you may find out is identical for some or all of them (you can try here: https://godbolt.org/).

As an aside, if your loop bodies are actually writing to cout on every iteration, it will not matter which loop style you use, because cout is slow and iterating integers in a vector is fast.

Upvotes: 2

Related Questions