Python is faster than C

Armin Rigo arigo at tunes.org
Sat Apr 3 19:59:40 EST 2004


Hi,

Joe Mason wrote:
> > The reason is that the C implementation must use a generic '<' operator
> > to compare elements, while the Psyco version quickly figures out that it
> > can expect to find ints in the list; it still has to check this
> > assumption, but this is cheap and then the comparison is done with a
> > single machine instruction.
> 
> Why can't the C implementation do the same thing?

You could, if you wanted to optimize specifically lists of integers.  If
you did the result would probably be really fast.  The problem is that
you can only really special-case so many types: the C code has to deal
with all cases without knowing which cases are likely.  The Psyco
version quickly figures out that for this list it pays off to make a
special case for integers; with another list, the machine code would be
different, special-cased differently.

However, in most real examples, you are not sorting a list of integers
but of something more complex anyway, where the built-in sort wins
easily.  My message was intended as a long-term hint that maybe, at some
point, the built-in sort will actually be more often faster than the C
one if rewritten in Python.  The advantage would then be that (as Psyco
does in a limited fashion) you can specialize the code for the
particular kind of list you are dealing with.


Armin



More information about the Python-list mailing list