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

Sean Harmer sean.harmer at maps-technology.com
Sat Nov 28 15:49:39 CET 2009


Hi,

M. Bashir Al-Noimi wrote:
> 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();

Sorry my bad. I shouldn't read code that late at night ;-)

Even so you are still not comparing like for like. In such a simple loop 
the way you incrmement the counter *might* important depending upon 
compiler and optimisation level. The foreach macro expands to a for loop 
itself - look up the Q_FOREACH macro in the Qt source tree. It is in the 
file qtglobal.h. However, the for loop there uses the prefix form of 
operator ++ rather than the postfix form you are using in your comparison.

Also in your for loop you are using the operator [] which is non-const 
and so the compiler cannot optimise this as much as if you used the 
equivalent at() const function call.

Others may also be able to point out some possible reasons why you get 
the results that you do.

Cheers,

Sean



More information about the Qt-interest-old mailing list