C++ iterators & loop optimization
I see a lot of c++ code that looks like this:
for( const_iterator it = list.begin(),
const_iterator ite = list.end();
it != ite; ++it)
As opposed to the more concise version:
for( const_iterator it = list.begin();
it != list.end(); ++it)
Will there be any difference in speed between these two conventions? Naively the first will be slightly faster since list.end() is only called once. But since the iterator is const, it seems like the compiler will pull this test out of the loop, generating equivalent assembly for both.
I'll just mention for the record that the C++ standard mandates that calling begin()
and end()
on any container type (be it vector
, list
, map
etc.) must take only constant time . In practice, these calls will almost certainly be inlined to a single pointer comparison if you compile with optimisations turned on.
Note that this guarantee does not necessarily hold for additional vendor-supplied "containers" that do not actually obey the formal requirements of being a container laid out in the chapter 23 of the standard (eg the singly-linked list slist
).
The two versions are not the same though. In the second version it compares the iterator against list.end()
every time, and what list.end()
evaluates to might change over the course of the loop. Now of course, you cannot modify list
through the const_iterator it
; but nothing prevents code inside the loop from just calling methods on list
directly and mutating it, which could (depending on what kind of data structure list
is) change the end iterator. It might therefore be incorrect in some circumstances to store the end iterator beforehand, because that may no longer be the correct end iterator by the time you get to it.
The first one will probably almost always be faster, but if you think this will make a difference, always profile first to see which is faster and by how much.
The compiler will probably be able to inline the call to end()
in both cases, although if end()
is sufficiently complicated, it may opt not to inline it. However, the key optimization is whether or not the compiler can perform loop-invariant code motion. I would posit that in most cases, the compiler can't be certain that the value of end()
won't change during the iteration of the loop, in which case it has no choice but to call end()
after each iteration.
上一篇: 什么是Linux上用于C ++的简单易用的探查器?
下一篇: C ++迭代器和循环优化