Ajay Ajay - 19 days ago 7
C++ Question

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

Which is better (or faster), a C++

for
loop or the
foreach
operator provided by Qt? For example, the following condition

QList<QString> listofstrings;


Which is 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
}

Answer

It really doesn't matter in most cases.

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

If you are really concerned, profile it for yourself and act on what you find.

But I think you'll most likely find that only in the most intense data-processing-heavy work does this question matter. The difference may well be only a couple of seconds and even then, only when processing huge numbers of elements.

Get your code working first. Then get it working fast (and only if you find an actual performance issue).

Time spent optimising before you've finished the functionality and can properly profile, is mostly wasted time.