Incrementing iterators: Is ++it more efficient than it++?(递增迭代器:++it 比 it++ 更高效吗?)
问题描述
可能重复:
i++和++之间是否存在性能差异我在 C++ 中?
我正在编写一个程序,其中使用迭代器循环 std::vector.有人告诉我,在 for 语句中执行 ++it 会导致代码更高效.换句话说,他们是在说:
I am writing a program where an iterator is used to loop through a std::vector. Somebody told me that doing ++it in the for statement leads to more efficient code. In other words, they are saying that:
for ( vector<string>::iterator it=my_vector.begin(); it != my_vector.end(); ++it )
跑得比
for ( vector<string>::iterator it=my_vector.begin(); it != my_vector.end(); it++ )
这是真的吗?如果是,效率提升背后的原因是什么?它++/++所做的只是将迭代器移动到向量中的下一项,不是吗?
Is this true? If it is, what is the reason behind the efficiency improvement? All it++/++it does is move the iterator to the next item in the vector, isn't it?
推荐答案
前置增量更快的原因是后置增量必须复制旧值才能返回.正如 GotW #2 所说,前增量比后增量更有效,因为对于后增量对象必须自增,然后返回一个包含其旧值的临时值.请注意,即使对于像 int 这样的内置函数也是如此."
The reason behind the preincrement being faster is that post-increment has to make a copy of the old value to return. As GotW #2 put it, "Preincrement is more efficient than postincrement, because for postincrement the object must increment itself and then return a temporary containing its old value. Note that this is true even for builtins like int."
GotW #55 提供了 postincrement 的规范形式,这表明它必须做预增量加上更多的工作:
GotW #55 provides the canonical form of postincrement, which shows that it has to do preincrement plus some more work:
T T::operator++(int)
{
T old( *this ); // remember our original value
++*this; // always implement postincrement
// in terms of preincrement
return old; // return our original value
}
正如其他人所指出的,某些编译器可能会在某些情况下对此进行优化,但如果您不使用返回值,最好不要依赖此优化.此外,对于具有微不足道的复制构造函数的类型,性能差异可能非常小,尽管我认为在 C++ 中使用预增量是一个好习惯.
As others have noted, it's possible for some compiler to optimize this away in some cases, but if you're not using the return value it's a good idea not to rely on this optimization. Also, the performance difference is likely to be very small for types which have trivial copy constructors, though I think using preincrement is a good habit in C++.
这篇关于递增迭代器:++it 比 it++ 更高效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:递增迭代器:++it 比 it++ 更高效吗?
基础教程推荐
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01