Is the ranged based for loop beneficial to performance?

前端 未结 5 1889
遥遥无期
遥遥无期 2020-12-02 18:34

Reading various questions here on Stack Overflow about C++ iterators and performance**, I started wondering if for(auto& elem : container) gets \"expan

5条回答
  •  自闭症患者
    2020-12-02 19:09

    Range-for is as fast as possible since it caches the end iterator[citation provided], uses pre-increment and only dereferences the iterator once.

    so if you tend to write:

    for(iterator i = cont.begin(); i != cont.end(); i++) { /**/ }
    

    Then, yes, range-for may be slightly faster, since it's also easier to write there's no reason not to use it (when appropriate).

    N.B. I said it's as fast as possible, it isn't however faster than possible. You can achieve the exact same performance if you write your manual loops carefully.

提交回复
热议问题