c++ - 基于范围的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
循环内部仅用于演示。
解决方案
预计它们中的任何一个都不会执行得更快或更慢。您必须测量才能在您的特定平台上找到答案。或者阅读汇编代码,您可能会发现其中一些或全部是相同的(您可以在这里尝试:https ://godbolt.org/ )。
顺便说一句,如果您的循环体实际上在每次迭代时都在写入cout
,那么您使用哪种循环样式并不重要,因为cout
它很慢并且在向量中迭代整数很快。
推荐阅读
- javascript - 如何使用 discord.js 编辑消息?
- javascript - 小吃吧,每次在 React 中显示的新计时器
- typescript - 如何从打字稿通用条件中“抛出”?
- reactjs - 如果道具是通过用户输入获得的,如何通过抽屉导航传递道具?
- ios - UICollectionView 布局错误的项目大小
- r - 按 id 和最近日期的条件 left_join
- python - python repli数据库抛出typeError
- php - 如何回显“未找到结果”。使用 sqlsrv 和 PHP?
- azure - Azure IoT 中心边缘模块“AzureVideoAnalyzerEdge”不会部署
- javascript - AssertionError:预期 [ Array(5) ] 具有属性“名称”