[Qt-interest] What is the best, "for" or "foreach"?
Sean Harmer
sean.harmer at maps-technology.com
Sat Nov 28 02:02:45 CET 2009
Hi,
M. Bashir Al-Noimi wrote:
> 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();
> }
>
> **
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.
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.
Sean
More information about the Qt-interest-old
mailing list