I know that the postfix versions of the increment/decrement operators will generally be optimised by the compiler for built-in types (i.e. no copy will be made), but is this the case for iterators?
They are essentially just overloaded operators, and could be implemented in any number of ways, but since their behaviour is strictly defined, can they be optimised, and if so, are they by any/many compilers?
#include <vector>
void foo(std::vector<int>& v){
for (std::vector<int>::iterator i = v.begin();
i!=v.end();
i++){ //will this get optimised by the compiler?
*i += 20;
}
}
In the specific case of
std::vectoron GNU GCC’s STL implementation (version 4.6.1), I don’t think there would be a performance difference on sufficiently high optimization levels.The implementation for forward iterators on
vectoris provided by__gnu_cxx::__normal_iterator<typename _Iterator, typename _Container>. Let’s look at its constructor and postfix++operator:And its instantiation in
vector:As you can see, it internally performs a postfix increment on an ordinary pointer, then passes the original value through its own constructor, which saves it to a local member. This code should be trivial to eliminate through dead value analysis.
But is it optimized really? Let’s find out. Test code:
Output assembly (on
-Os):As you can see, exactly the same assembly is output in both cases.
Of course, this may not necessarily be the case for custom iterators, or more complex data types. But it appears that, for
vectorspecifically, prefix and postfix (without capturing the postfix return value) have identical performance.