[Qt-interest] What is the best, "for" or "foreach"?
Sean Harmer
sean.harmer at maps-technology.com
Sat Nov 28 17:35:39 CET 2009
Hi,
On Saturday 28 November 2009 16:28:30 Paul Miller wrote:
> 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.
QList always has constant access time though. It is just that when the type
being stored is larger than a pointer, the constant also includes the time to
perform the extra pointer redirection since QList stores a vector of pointers
in this case.
This table compares the speed of various operations on the Qt container
classes:
http://doc.trolltech.com/4.6-snapshot/containers.html#algorithmic-complexity
Cheers,
Sean
More information about the Qt-interest-old
mailing list