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
从不修改,并遵守const正确性,所以我可以做:
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
)总是优先的,因为没有额外的副本增加的效率( EDIT : 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
?
我正在开发中,我正在考虑进行这种变化,因为效率是至关重要的(我在Cist使用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屋!