[Python-Dev] Comparison speed
Barry A. Warsaw
barry@digicool.com
Tue, 15 May 2001 18:56:10 -0400
>>>>> "JH" == Jeremy Hylton <jeremy@digicool.com> writes:
JH> I only learned recently that isinstance() can be called with
JH> types instead of classes. I suppose the name lead me in the
JH> wrong direction. I had the silly idea that it only applied to
JH> instances <0.1 wink>.
JH> So it comes as little surprise to me that there is a lot of
JH> code executed in, e.g., the test suite that does comparisons
JH> on types.
JH> In the Lib directory, there are 63 files that use == and the
JH> builtin type function. (Simple grep.) A total of 139
JH> instances of this idiom. A cursory scan suggests that most of
JH> the call are things like type(obj) == type('').
Even without the forward-looking insight that types are classes
<wink>, I think type comparisions should have been done with `is' and
not ==. So old school type comparisons should have been done as
type(obj) is StringType
whereas new school type comparisons should be done as
isinstance(obj, StringType)
With Python 2.1 == is naturally, slower than `is', but isinstance()
comes in somewhere in the middle.
563897.802881 is comparisons per second
506827.201066 == comparisons per second
520696.916088 isinstance() comparisons per second
-Barry
-------------------- snip snip --------------------
from types import StringType
import time
r = range(1000000)
def one(r=r):
x = 'hello'
t0 = time.time()
for i in r:
type(x) is StringType
t1 = time.time() - t0
print len(r) / t1, 'is comparisons per second'
def two(r=r):
x = 'hello'
t0 = time.time()
for i in r:
type(x) == StringType
t1 = time.time() - t0
print len(r) / t1, '== comparisons per second'
def three(r=r):
x = 'hello'
t0 = time.time()
for i in r:
isinstance(x, StringType)
t1 = time.time() - t0
print len(r) / t1, 'isinstance() comparisons per second'
one()
two()
three()