[Qt-interest] What is the best, "for" or "foreach"?
Sean Harmer
sean.harmer at maps-technology.com
Sat Nov 28 17:10:19 CET 2009
Hi,
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.
Sean
More information about the Qt-interest-old
mailing list