Difference between 'is' and '=='

Joel Hedlund joel.hedlund at gmail.com
Tue Mar 28 05:12:52 EST 2006


> a is None
> 
> is quicker than
> 
> a == None

I think it's not such a good idea to focus on speed gains here, since they 
really are marginal (max 2 seconds total after 10000000 comparisons):

 >>> import timeit
 >>> print timeit.Timer("a == None", "a = 1").timeit(int(1e7))
4.19580316544
 >>> print timeit.Timer("a == None", "a = None").timeit(int(1e7))
3.20231699944
 >>> print timeit.Timer("a is None", "a = 1").timeit(int(1e7))
2.37486410141
 >>> print timeit.Timer("a is None", "a = None").timeit(int(1e7))
2.48372101784

Your observation is certainly correct, but I think it's better applied to more 
complex comparisons (say for example comparisons between gigantic objects or 
objects where value equality determination require a lot of nontrivial 
computations). That's where any real speed gains can be found. PEP8 tells me 
it's better style to write "a is None" and that's good enough for me. Otherwise 
I try to stay away from speed microoptimisations as much as possible since it 
generally results in less readable code, which in turn often results in an 
overall speed loss because code maintenance will be harder.

Cheers!
/Joel Hedlund



More information about the Python-list mailing list