C++11基于范围的for循环效率“const auto &i"与“自动 i" [英] C++11 Range-based for-loop efficiency "const auto &i" versus "auto i"
问题描述
在 C++11 中,我可以像这样迭代某个容器:
In C++11, I can iterate over some container like so:
for(auto i : vec){
std::cout << i << std::endl;
}
但我知道这是不必要的 - 不必要,因为我只需要打印 vec
的值 - 复制 (EDIT:每个元素)vec
,所以我可以这样做:
But I know that this needlessly - needlessly, since I only need to print the values of vec
- makes a copy of (EDIT: each element of) vec
, so instead I could do:
for(auto &i : vec){
std::cout << i << std::endl;
}
但我想确保 vec
的值永远不会被修改并遵守常量正确性,所以我可以这样做:
But I want to make sure that the values of vec
are never modified and abide by const-correctness, so I can do:
for(const auto &i : vec){
std::cout << i << std::endl;
}
所以我的问题是:如果我只需要查看某个容器的值,那么最后一个循环 (const auto &i
) 不会总是由于没有额外副本(编辑:vec
的每个元素)vec
?
So my question is: If I only need to look at the values of some container, wouldn't the very last loop (const auto &i
) always be preferred due to the increased effieciency of not having an extra copy of (EDIT: each element of) vec
?
我正在开发一个程序,我正在考虑在其中进行此更改,因为效率在其中至关重要(这是我首先使用 C++ 的原因).
I have a program that I'm developing in which I'm considering making this change throughout, since efficiency is critical in it (the reason I'm using C++ in the fist place).
推荐答案
是的.同样的原因,如果你只读过一个参数,你就会将参数设为 const&
.
Yes. The same reason if you only ever read an argument you make the parameter const&
.
T // I'm copying this
T& // I'm modifying this
const T& // I'm reading this
那些是您的默认设置".但是,当 T
是基本类型(内置)时,您通常只需恢复到 const T
(无引用)进行读取,因为副本比别名更便宜.
Those are your "defaults". When T
is a fundamental type (built-in), though, you generally just revert to const T
(no reference) for reading, because a copy is cheaper than aliasing.
我正在开发一个程序,我正在考虑在其中进行此更改,因为效率在其中至关重要
I have a program that I'm developing in which I'm considering making this change throughout, since efficiency is critical in it
- 不要盲目地进行彻底的改变.一个有效的程序比一个快速但损坏的程序要好.
- 你如何迭代你的循环可能不会有太大的不同;你循环是有原因的,不是吗?循环体更有可能是罪魁祸首.
- 如果效率至关重要,您希望使用分析器来查找程序的哪些部分实际上很慢,而不是猜测可能 慢一点.请参阅 #2,了解为什么您的猜测可能是错误的.
- Don't make blind sweeping changes. A working program is better than a fast but broken program.
- How you iterate through your loops probably won't make much of a difference; you're looping for a reason, aren't you? The body of your loop will much more likely be the culprit.
- If efficiency is critical, you want to use a profiler to find which parts of your program are actually slow, rather than guess at parts that might be slow. See #2 for why your guess may be wrong.
这篇关于C++11基于范围的for循环效率“const auto &i"与“自动 i"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!