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

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

 QList<QString> listofstrings; 

What's better?

 foreach(QString str, listofstrings) { //code } 

or

 int count = listofstrings.count(); QString str = QString(); for(int i=0;i<count;i++) { str = listofstrings.at(i); //Code } 
+42
c ++ performance foreach for-loop qt
Apr 21 '09 at 4:12
source share
11 answers

In most cases, this does not matter.

A large number of questions on StackOverflow regarding whether this method or this method is faster claim that in the vast majority of cases, the code spends most of its time sitting around waiting for users to do something.

If you are really worried, comment on this for yourself and act on what you find.

But I think you will most likely find that only in the most intensive work with data processing does this issue matter. The difference can be only a couple of seconds and even then, only when processing a huge number of elements.

Download your code first. Then run it quickly (and only if you find an actual performance issue).

The time spent on optimizing before you finish functioning and can properly profile is basically a waste of time.

+139
Apr 21 '09 at 4:19
source share

First of all, I would like to say that I agree with Pax and that speed is probably not included in it. foreach wins hands on the basis of readability, and this is enough in 98% of cases.

But of course, the Qt guys studied it and actually did some profiling: http://blog.qt.io/blog/2009/01/23/iterating-efficiently/

The main lesson that needs to be removed is this: use const references in read-only loops, as this avoids creating temporary instances. It also makes the purpose of the loop more explicit, regardless of the cycling method used.

+18
Apr 21 '09 at 16:07
source share

It really doesn't matter . Most likely, if your program is slow, this is not a problem. However, it should be noted that you are not making absolutely equal comparisons. Qt foreach more like this (this example will use QList<QString> ):

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

A macro can do this using some compiler extensions (for example, GCC __typeof__ ) to get the type of container passed. Also imagine that boost BOOST_FOREACH very similar in concept.

The reason your example is unfair is because your non-Qt version adds extra work.

Instead of indexing, you are indexing. If you are using a type with non-contiguous distribution (I suspect this may be the case with QList<> ), then indexing will be more expensive since the code must calculate the "where" n-th element.

It is said. It doesn't matter yet . The time difference between the two pieces of code will be negligible, if at all. Do not waste time worrying about it. Write which one you find more understandable and understandable.

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

 for(QString &s : Con) { // you code here } 
+14
Apr 21 '09 at 17:27
source share

I do not want to answer the question which is faster, but I want to say which is better.

The biggest problem with Qt foreach is that before it repeats, a copy of your container is executed. You could say, β€œIt doesn't matter because the Qt classes are recounted,” but since the copy is used, you are not actually modifying the original container.

Thus, Qt foreach can only be used for read-only loops, and this should be avoided. Qt will gladly allow you to write a foreach loop, which, in your opinion, will update / modify your container, but in the end all changes will be deleted.

+9
Apr 25 '09 at 14:13
source share

First, I completely agree with the answer that "it does not matter." Choose the cleanest solution and optimize if this becomes a problem.

But another way to look at this is that often the fastest solution is the one that most accurately describes your intentions. In this case, QT foreach says that you want to apply some kind of action for each element in the container.

Simple for the loop says you need an i counter. You want to re-add one to this i value, and while it is less than the number of elements in the container, you would like to perform some action.

In other words, an equal for the loop once again poses a problem. It adds many requirements that are not really part of what you are trying to do. You do not care about the loop counter. But as soon as you write a for loop, it should be there.

On the other hand, QT people have not made any additional promises that could affect performance. They simply guarantee iteration through the container and apply an action to each.

In other words, often the cleanest and most elegant solution is also the fastest.

+3
Apr 21 '09 at 16:53
source share

Qt's foreach has a clearer syntax for the for IMHO loop, so it is better in that sense. I am sure there is something to it.

Instead, you can use BOOST_FOREACH , since it is a well-thought out loop for a loop, and it carries over (and presumably this will be the way in C ++ some day and is future proof too).

+2
Apr 21 '09 at 4:21
source share

The test and its results can be found at http://richelbilderbeek.nl/CppExerciseAddOneAnswer.htm

IMHO (and many others here) this (that is, speed) does not matter.

But feel free to draw your own conclusions.

+2
Jul 25 '10 at 9:52
source share

For small collections, this should make a difference, and foreach tends to be clearer.

However, for large collections, at some point the foreach will begin to beat. (assuming that the operator at () 'is efficient.

If this is really important (and I assume that this is how you ask), then it is best to measure it. The profiler needs to do the trick, or you can create a test version using some tools.

+1
Apr 21 '09 at 4:26
source share

Since Qt 5.7 the foreach macro is deprecated, Qt recommends you use C ++ 11 for .
http://doc.qt.io/qt-5/qtglobal.html#foreach

(more about the difference here: https://www.kdab.com/goodbye-q_foreach/ )

+1
Aug 16 '17 at 11:17
source share

I would expect foreach to work nominally faster in some cases, and about the same in others, except when the elements are an actual array, in which case the performance difference is not significant.

If implemented on top of a counter, it may be more efficient than direct indexing, depending on the implementation. This is unlikely to be less effective. For example, if someone put up a balanced tree, both indexed and enumerable, then foreach will be decently faster. This is due to the fact that each index will have to find the reference element on its own, while the enumerator has the context of the current node in order to more effectively move to the next ont.

If you have an actual array, it depends on the implementation of the language and class, whether foreach will be faster for the same as for.

If indexing is a literal memory offset (e.g. C ++), then this should be a little faster, since you avoid calling the function. If indexing is indirect, like a challenge, then it should be the same.

All that has been said ... It is difficult for me to find here a case of generalization. This is the last kind of optimization you should look for, even if your application has performance issues. If you have a performance problem that can be solved by changing the way you repeat, you really have no performance problem. You have a BUG because someone wrote either a very crappy iterator or a really crappy index.

0
Apr 21 '09 at 4:50
source share

You can look at the STL for_each function. I don’t know if it will be faster than the two options that you present, but it is more standardized than Qt foreach, and avoids some problems that you may encounter with a regular loop (namely, due to indexing restrictions and difficulties with the transfer of the cycle to another data structure).

0
Apr 21 '09 at 15:09
source share



All Articles