[Qt-interest] What is the best, "for" or "foreach"?

Paul Miller paul at fxtech.com
Sat Nov 28 17:05:28 CET 2009


M. Bashir Al-Noimi wrote:
> I've wrote the following snippet for testign the speed of "for" and 
> "forech" loops and I noticed that "foreach" faster than "for" about 2 
> times! >:o
> 
> *Is "foreach" faster than "for"?*

The reason your particular example is faster with the foreach is because 
foreach is using an iterator and your for loop is looping over the 
actual list indexes. But, since you're using a QList<>, each access of 
the list in the for loop is linear time, since QList<> is not 
random-accessible.

In other words, the two loops are vastly different in how they iterate 
over the list.

You can make both loops the same speed by replacing the QList<> with 
QVector<>, which allows constant time access via the [] operator.

Or, you can prefer using iterators to walk the list as long as you don't 
need random access. You can write the equivalent loop yourself using 
iterators like this:

QListIterator<int> iter(list);
while (iter.hasNext())
{
     int value = iter.next();
     // use value
}

-- 
Paul Miller | paul at fxtech.com | www.fxtech.com | Got Tivo?




More information about the Qt-interest-old mailing list