提问者:小点点

基于范围的for循环的range_declaration中各种说明符的性能差异


我见过在为基于范围的for循环声明范围时使用的许多类型说明符,如:

#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

预计哪一种性能更快(在-O2或-O3优化后)? 选择是否取决于vector的数据类型,还是取决于我们在循环中执行的操作。

附注:循环内的cout仅用于演示。


共1个答案

匿名用户

预计他们中的任何一个都不会有更快或更慢的表现。 您必须在您的特定平台上进行测量才能找到答案。 或者阅读汇编代码,您可能会发现它们中的一些或全部是相同的(您可以在这里尝试:https://godbolt.org/)。

顺便说一句,如果您的循环体在每次迭代时都要写cout,那么使用哪种循环样式并不重要,因为cout比较慢,而在向量中迭代整数比较快。