[FRPythoneers] Python documentation and default expression
chyser at yahoo.com
Fri Mar 15 22:48:08 MST 2002
I'm new to the list. As a long time C and C++ programmer (still trying to make the mental leap to interpreted languages for anything beyond simple scripting jobs), I'm interested in python performance issues. Did a simple experiment below:
Matt Gushee <mgushee at havenrock.com> wrote:
On Fri, Mar 15, 2002 at 06:16:36PM -0700, Jeffery D. Collins wrote:
>> > I've almost always used "if foo != None:". Is there a reason not to
>> > write it as such?
>There may be in some applications.
>The "is" compares object identities and the "==" ("!=") compares object
>> Since None is a singleton and comparisons are always done wrt to its
>> the results will be identical.
>That's all true, but there are performance differences that may be
>significant if you are iterating over a large set of objects. I've done
>an informal benchmark. Since the actual comparison is probably the least
>expensive part of the test function, I'd say the ~25% difference I'm
>seeing is quite significant. This will undoubtedly vary according to
>platform, Python implementation, etc. I ran this on Linux (kernel 2.2.19,
>glibc 2.1) with cPython 2.1. I also did a similar test comparing two
>integers, which found no significant differences between 'is' and '=='.
>Presumably '==' is more expensive on class instances because it involves
>inspecting the object, whereas an 'is' comparison just uses the object
>ID -- or something like that.
When performing an equality comparison with an object, an attempt to look up various attributes will occur. First it will look for __ne__, if not found __cmp__ and finally check for ID (ie object address) equality (what 'is not' gets you in the first place.)
>>> class cool:
... def __cmp__(self, x):
... print 'cmp'
... return 0
>>> c = cool()
>>> if c != None:
>>> if c is not None: print "cool"
So 'is not" will avoid attribute lookup attempts which has to be more expensive than the interpreter simply comparing two C pointers.
Do You Yahoo!?
Yahoo! Sports - live college hoops coverage
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the FRPythoneers