'for' loop vs Qt's 'foreach' in C++

前端 未结 11 848
我寻月下人不归
我寻月下人不归 2020-12-14 05:28

Which is better (or faster), a C++ for loop or the foreach operator provided by Qt? For example, the following condition

QList

        
11条回答
  •  天涯浪人
    2020-12-14 06:07

    First off, I'd just like to say I agree with Pax, and that the speed probably doesn't enter into it. foreach wins hands down based on readability, and that's enough in 98% of cases.

    But of course the Qt guys have looked into it and actually done some profiling: http://blog.qt.io/blog/2009/01/23/iterating-efficiently/

    The main lesson to take away from that is: use const references in read only loops as it avoids the creation of temporary instances. It also make the purpose of the loop more explicit, regardless of the looping method you use.

提交回复
热议问题