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

M. Bashir Al-Noimi mbnoimi at gmx.com
Sat Nov 28 01:04:05 CET 2009


Hi All,

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"?*

Another question:

*Can I use "foreach" for modifying container items just like for?*

*
*

#include <QtCore/QCoreApplication>
#include <QTime>
#include <iostream>
using namespace std;
#define COUNT 100000000

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QList<int> list;
    QTime classicTimer, qtTimer;
    int classicDuration, qtDuration;
    int temp;
    // input
    for(int x=0; x<COUNT; x++)
        list<<0;
    // qt loop
    qtTimer.start();
    foreach(int var, list)
       temp = var;
    qtDuration = qtTimer.elapsed();
    // classic loop
    classicTimer.start();
    for(int x=0; x<COUNT; x++)
        temp = list[x];
    classicDuration = classicTimer.elapsed();

    // The results
    cout<<"\n\n\n"
            <<"Classic loop: "<<classicDuration
            <<"\nQt loop: "<<qtDuration;
    return a.exec();
}

**



-----
Best Regards
Muhammad Bashir Al-Noimi
My Blog: http://mbnoimi.net/

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20091128/e26878a4/attachment.html 


More information about the Qt-interest-old mailing list