首页 > 解决方案 > 基于范围的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 优化之后)?选择取决于向量的数据类型,还是取决于我们在循环内执行的操作。

PS:cout循环内部仅用于演示。

标签: c++

解决方案


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

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


推荐阅读