c++ - 基于范围的for循环的range_declaration中各个说明符之间的性能差异

标签 c++

在为基于范围的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的数据类型,还是取决于我们在循环内部执行的操作。
PS:循环内的cout仅用于演示。

最佳答案

预期它们都不会表现得更快或更慢。您必须采取措施才能在您的特定平台上找到答案。或阅读汇编代码,您可能会发现其中的一部分或全部是相同的(可以在此处尝试:https://godbolt.org/)。
顺便说一句,如果您的循环体实际上在每次迭代中都写入cout,则使用哪种循环样式都没有关系,因为cout很慢并且 vector 中的整数迭代很快。

关于c++ - 基于范围的for循环的range_declaration中各个说明符之间的性能差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62497276/

相关文章:

使用 Boost Python 的 Python 性能没有 boost

c++ - 静态成员显式定义

c++ - 使用 cvtColor 转换单一颜色

c++ - cv::Mat 转换为特征矩阵并返回

c++ - 如何获取样式表设置的Qt中小部件的字体?

c++ - 直接调用函数与发出信号(Qt - 信号和槽)

c++ - 用于 C++ 应用程序的 SMART ASSERT?

c++ - "CopyConstructible"对 C++ STL 容器元素的要求

c++ - 了解反转字符串的代码

c++ - 如何在模板函数中使用 C++ 字符串文字?