C++ iterators & loop optimization

前端 未结 11 1365
渐次进展
渐次进展 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:38

    In theory the compiler could optimise the second version into the first (assuming the container doesn't change during the loop, obviously).

    In practice, I've found several similar cases when profiling time-critical code where my compiler has totally failed to hoist invariant calculations out of loop conditions. So while the slightly more concise version is fine in most cases, I don't rely on the compiler doing sensible things with it for a case where I'm really concerned about performance.

提交回复
热议问题