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

前端 未结 11 849
我寻月下人不归
我寻月下人不归 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:19

    It really doesn't matter. Odds are if your program is slow, this isn't the problem. However, it should be noted that you aren't make a completely equal comparison. Qt's foreach is more similar to this (this example will use QList):

    for(QList::iterator it = Con.begin(); it != Con.end(); ++it) {
        QString &str = *it;
        // your code here
    }
    

    The macro is able to do this by using some compiler extensions (like GCC's __typeof__) to get the type of the container passed. Also imagine that boost's BOOST_FOREACH is very similar in concept.

    The reason why your example isn't fair is that your non-Qt version is adding extra work.

    You are indexing instead of really iterating. If you are using a type with non-contiguous allocation (I suspect this might be the case with QList<>), then indexing will be more expensive since the code has to calculate "where" the n-th item is.

    That being said. It still doesn't matter. The timing difference between those two pieces of code will be negligible if existent at all. Don't waste your time worrying about it. Write whichever you find more clear and understandable.

    EDIT: As a bonus, currently I strongly favor the C++11 version of container iteration, it is clean, concise and simple:

    for(QString &s : Con) {
        // you code here
    }
    

提交回复
热议问题