PDA

View Full Version : QList speed



timmu
11th September 2012, 09:06
Which of the two scenarios is faster?

1. Build a QList with for loop and append()
2. Use the QList
3. Delete the QList with clear()
4. Cycle back to step 1 several millions of times

1. Build a QList with for loop and append()
2. Use the QList
3. Zero the QList with a for loop
4. Cycle back to step 2 several millions of times

The Qlist is <double> and its size is about 5000

So, basiclly what I'm, asking is: which is faster a) append()+clear(), or b) using the for loop to reassing.
I'm suspecting the latter is faster but I don't know enough about how QList works.

wysota
11th September 2012, 09:43
If you know the number of items upfront (so that you can reserve space for all items in one go) then they are (more or less) equally fast.

spirit
11th September 2012, 09:46
If you look at QList implementation you'll find the following code for the clear:


...
Q_OUTOFLINE_TEMPLATE void QList<T>::clear()
{
*this = QList<T>();
}
...

You might also look at implementation of assignment operator:


Q_INLINE_TEMPLATE QList<T> &QList<T>::operator=(const QList<T> &l)
{
if (d != l.d) {
QListData::Data *o = l.d;
o->ref.ref();
if (!d->ref.deref())
free(d);
d = o;
if (!d->sharable)
detach_helper();
}
return *this;
}

So, as you can see, there are d-pointer's data copy and ref-counting operations.

timmu
11th September 2012, 11:05
So, basically it is fair to say that building ( append() ) and clearing ( clear() ) a QList is a fast way of doing things? I shouldn't replace as many append()/clear() pairs with loops assigning new values to existing QList to gain speed?

amleto
11th September 2012, 13:58
how slow is your app? how much time do you hope to gain? have you ran profilers and found this area to be a bottle neck?

The two options are very easy to test. So why don't you test and compare?

Lesiok
11th September 2012, 15:39
Remeber that QList in debug mode have many asserts and is about several times slower than in release mode.

wysota
11th September 2012, 15:43
So, basically it is fair to say that building ( append() ) and clearing ( clear() ) a QList is a fast way of doing things? I shouldn't replace as many append()/clear() pairs with loops assigning new values to existing QList to gain speed?

It depends whether you know how many items you are going to have. Most of append() cost is reallocating memory. If you allocate a lot, it will be slower than reassigning data to existing cells in the list.

amleto
11th September 2012, 17:47
most appends wont be allocating memory though...