首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于范围的for循环的range_declaration中不同说明符的性能差异

基于范围的for循环的range_declaration中不同说明符的性能差异
EN

Stack Overflow用户
提问于 2020-06-21 10:26:50
回答 1查看 61关注 0票数 1

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

代码语言:javascript
复制
#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只是为了演示。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-21 10:41:59

他们中没有人被期望表现得更快或更慢。你必须通过测量才能在你的平台上找到答案。或者阅读程序集代码,您可能会发现它们中的一些或全部是相同的(您可以在这里尝试:https://godbolt.org/)。

另外,如果您的循环体实际上是在每次迭代中写入cout,那么使用哪种循环样式并不重要,因为cout速度慢,而且向量中的整数迭代速度很快。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62497276

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档