C++ iterators & loop optimization

前端 未结 11 1149
渐次进展
渐次进展 2021-01-30 04:11

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)
<
11条回答
  •  醉梦人生
    2021-01-30 04:41

    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.

提交回复
热议问题