增加迭代器:++它比++更有效吗? [英] Incrementing iterators: Is ++it more efficient than it++?

查看:144
本文介绍了增加迭代器:++它比++更有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

C ++中的i ++和++ i之间是否存在性能差异?

我正在编写一个程序,其中迭代器用于循环std :: vector。有人告诉我,在for语句中执行++会导致更高效的代码。换句话说,他们说:

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?

推荐答案

preincrement背后更快的原因是后增量必须复制旧值才能返回。正如 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 提供了后增量的规范形式,表明它必须进行预增量再加上一些工作:

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 ++中使用preincrement是一个好习惯。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆