Result of ``a is b''

David M. Cooke cookedm+news at physics.mcmaster.ca
Thu Mar 18 01:17:53 EST 2004


At some point, David MacQuigg <dmq at gain.com> wrote:

> On Tue, 16 Mar 2004 18:00:04 -0500, cookedm+news at physics.mcmaster.ca
> (David M. Cooke) wrote:
>
>>Personally, almost all my uses of 'is' are of the form 'x is None' or
>>'x is not None'.
>
> Here are some more test results (averaging 10,000 evaluations in a
> tight loop):
>
>         time (sec)    %
> Test 1: 3.68E-007   100.0 F is False
> Test 2: 4.87E-007   132.1 F == False
> Test 3: 3.71E-007   100.0 N is None
> Test 4: 5.51E-007   148.6 N == None
>
> The '== None' test is 49% slower than 'is None', but in absolute time,
> the difference is only 180nec (on my new, but not top-speed PC).  So
> it would take about 10 million of these comparisons in a short time to
> make a noticable difference to the user.
>
> I can't see where the 'is' test would *ever* be needed for the above
> comparisons.

I do a lot of stuff with arrays in Numeric, which override __eq__ to
elementwise comparision:

Python 2.3.3 (#2, Feb 24 2004, 09:29:20) 
[GCC 3.3.3 (Debian)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import Numeric
>>> x = Numeric.array([0,1,2,3])
>>> x == None
array([0,0,0,0])
>>> bool(x == None)
False
>>> x is None
False
>>> x == False
array([1,0,0,0])
>>> bool(x == False)
True
>>> x is False
False
>>> bool(x == True)
True
>>> bool(x == True and x == False)
True

[Ok, so bool(x == None) returns False, which is good, but imagine the
overhead if x was an array of several million elements. x == None
would allocate a new array of the same size.]

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca



More information about the Python-list mailing list