Incrementing iterators: Is ++it more efficient than it++?(递增迭代器:++it 比 it++ 更有效吗?)
问题描述
Possible Duplicate:
Is there a performance difference between i++ and ++i in C++?
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 )
runs faster than
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?
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 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
}
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++ 更有效吗?
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01