[英]Performance difference between various specifiers in range_declaration of range-based for loop
我已經看到在為基於范圍的 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
很慢,而在向量中迭代整數很快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.