list.sort(func) speed

Chad Netzer cnetzer at sonic.net
Sun Aug 31 22:15:11 CEST 2003


On Sun, 2003-08-31 at 12:07, mackstann wrote:

> > Personally, I would go with a Song class, where the artist, length etc.
> > could successively be added, but that would rather be trading speed for
> > features...
> 
> Yeah, I have thought about it, and it would definitely be the more OOPey
> way to go, but I figured that anyone using this with 20,000 files would
> get a little grumpy at the speed hit. :)

There is nothing about using a class that will make your program
inherently slow, as long as you use the right algorithms.

A data set of 20,000 is *small* by todays standards.  Sorting it should
be trivial and near instantaneous using decorate-sort-undecorate.  Once
it is sorted, you just keep the list sorted by doing insertions in
sorted order (a very fast operation).  Is there a reason you need to do
lots of re-sorts?

Perhaps you can use a dict to hold your data.  You can also extract all
the keys you need to sort on, ahead of time, and keep it paired up with
you data class or dictionary.  This will make decorate-sort-undecorate
easy to code, and very quick to execute.  And you still have a flexible,
easy to use data type.

I'd strongly suggest you not avoid dicts or classes, just to try to
speed up your code.  Almost all the time, they do not impair
performance.  And if you complicate your design by avoiding them, you
are putting yourself through unneeded pain.

-- 
Chad Netzer






More information about the Python-list mailing list