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

M. Bashir Al-Noimi mbnoimi at gmx.com
Sat Nov 28 15:07:13 CET 2009


Sean Harmer wrote:
> You are not doing a fair test. Your "for" loop is performing memory 
> allocations by appending to the list. Your foreach loop is not doing 
> any memory allocations so it is very likely to be quicker. You are 
> comparing apples and oranges here.
I think you didn't read the code carefully.
The timer starts after appending process for making the test fair.

    // 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();



>
> Also foreach is quicker if you use a const ref. i.e.
>
> foreach( const int& var, list )
>     doSomething( var );
>
> May not be a big difference for an int but it will be for 
> large/complex objects.
It gave me same result!

P.S
All for giving a fair result I took 10 tests each time.




-----
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/1020b57c/attachment.html 


More information about the Qt-interest-old mailing list