Many times I have read that using "for(int i=0; i<size; i++)" to iterate list is bad idea and we must use STL or Java style iterators. I decided to make my own research and calculate processing time for each iterating method. I made 5 trials and calculated average time.
QList<int> list;
int size = 100000000;
for(int i = 0; i < size; i++)
list.append(1);
int sum = 0;
qint64 begin
= QDateTime::currentMSecsSinceEpoch();
//Simplest method
for(int i = 0; i < size; i++)
sum += list.at(i);
//Java-style iterator
QListIterator<int> it(list);
while(it.hasNext())
sum += it.next();
//STL-style iterator
QList<int>::iterator i;
for(i = list.begin(); i != list.end(); ++i)
sum += *i;
qint64
time = QDateTime::currentMSecsSinceEpoch() - begin;
qDebug() << "Time: " << time;
QList<int> list;
int size = 100000000;
for(int i = 0; i < size; i++)
list.append(1);
int sum = 0;
qint64 begin = QDateTime::currentMSecsSinceEpoch();
//Simplest method
for(int i = 0; i < size; i++)
sum += list.at(i);
//Java-style iterator
QListIterator<int> it(list);
while(it.hasNext())
sum += it.next();
//STL-style iterator
QList<int>::iterator i;
for(i = list.begin(); i != list.end(); ++i)
sum += *i;
qint64 time = QDateTime::currentMSecsSinceEpoch() - begin;
qDebug() << "Time: " << time;
To copy to clipboard, switch view to plain text mode
Results surprised me. Simplest "stupid" method took 85 ms, Java-style iterator 111 ms and STL-iterator 260 ms. It seems that for simple iteration over all list's elements "for(int i=0; i<size; i++)" method will be the fastest.
Bookmarks