[Qt-interest] What is the best, "for" or "foreach"?
Paul Miller
paul at fxtech.com
Sat Nov 28 17:28:30 CET 2009
Sean Harmer wrote:
> Paul Miller wrote:
>> M. Bashir Al-Noimi wrote:
>>> 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"?*
>>
>> The reason your particular example is faster with the foreach is
>> because foreach is using an iterator and your for loop is looping over
>> the actual list indexes. But, since you're using a QList<>, each
>> access of the list in the for loop is linear time, since QList<> is
>> not random-accessible.
>
> I'm sorry but that is wrong. From the docs of QList:
>
> "Internally, QList<T> is represented as an array of pointers to items of
> type T. If T is itself a pointer type or a basic type that is no larger
> than a pointer, or if T is one of Qt's shared classes, then QList<T>
> stores the items directly in the pointer array."
>
> So for types where sizeof( type ) <= sizeof( pointer ) a QList is just
> the same as a QVector - except that it also pre-allocates extra space at
> the beginnging whereas QVector doesn't.
Ah, good to know. When I use it, I use it under the assumption that it
acts like a linked list. I prefer QVector<> for things that are meant to
be stored contiguously.
IMHO, having QList<> act like a QVector<> under certain circumstances is
an implementation detail that muddies the waters a bit.
--
Paul Miller | paul at fxtech.com | www.fxtech.com | Got Tivo?
More information about the Qt-interest-old
mailing list