[FRPythoneers] performance of cmp()

Rob Riggs rob at pangalactic.org
Tue Sep 23 09:06:46 MDT 2003

Rahul Kumar wrote:

>Knowing that 2 string comparisons are inefficient I found the cmp()
>method and did:
>i = cmp(a,b)
>To my surprise the second version kept performing *slower* than the
>first. Why this (unexpected) behavior?
If you think that two string compares are inefficient, just wait until 
you hear about the inefficiencies of interpreted languages!

Seriously, the first example you gave is more legible (and therefore 
more maintainable) than the second.  However, I grant that if 
performance is a concern here, a strcmp()-like function will be more 

The reason it is slower to do a cmp() is that strings do not have a 
builtin __cmp__() function, but instead use "rich comparisons" which 
means that cmp() is doing the same tests as your first example but with 
additional overhead.  For info, see 
http://www.python.org/doc/current/ref/customization.html and look at the 
__lt__() et al functions and  __cmp__().

To be honest, Python has never dealt with strings very efficiently.  
This is yet another example.


More information about the FRPythoneers mailing list