typechecks: just say no! (was Re: Determining Types)

Emile van Sebille emile at fenx.com
Mon Sep 3 17:57:18 EDT 2001


"Skip Montanaro" <skip at pobox.com> wrote in message
news:15251.48786.329817.450337 at localhost.localdomain...
>
>     Emile> Couldn't you always coerce it?
>     Emile> str('hello')
>     Emile> str(123)
>
> Yes, I could, but the problem arises quite rarely.  It seems to me that
> checking the type is going to generally be faster than always coercing.
>

It appears that always coercing is faster.

--

Emile van Sebille
emile at fenx.com

---------
from time import time

def test_arg(arg):
  if type(arg) == type(1):
    return str(arg)
  else:
    return arg

def coerce_arg(arg):
  return str(arg)

mostlyNums = range(1000)
for i in range(100):
  mostlyNums[i*9] = str(i)

mostlyStrs = map(str, range(1000))
for i in range(100):
  mostlyStrs[i*9] = i*9

for count in (100, 300, 1000):
  for args in (mostlyNums, mostlyStrs):
    print '\n\n---%s---(%s)' % (count, repr(args[1])),
    for iterations in (10, 25, 100):
      print "\n\n    %6d : " % iterations,
      for func in (test_arg, coerce_arg):
        print '  ',func.__name__,
        start = time()
        for i in range(iterations):
          for arg in args:
            func(arg)
        print '%6.2f' % (time()-start),


---100---(1)
        10 :     test_arg   0.17    coerce_arg   0.12
        25 :     test_arg   0.45    coerce_arg   0.31
       100 :     test_arg   1.79    coerce_arg   1.21
---100---('1')
        10 :     test_arg   0.11    coerce_arg   0.06
        25 :     test_arg   0.25    coerce_arg   0.17
       100 :     test_arg   0.99    coerce_arg   0.65
---300---(1)
        10 :     test_arg   0.18    coerce_arg   0.13
        25 :     test_arg   0.45    coerce_arg   0.30
       100 :     test_arg   1.79    coerce_arg   1.22
---300---('1')
        10 :     test_arg   0.10    coerce_arg   0.07
        25 :     test_arg   0.25    coerce_arg   0.16
       100 :     test_arg   0.98    coerce_arg   0.65
---1000---(1)
        10 :     test_arg   0.18    coerce_arg   0.12
        25 :     test_arg   0.45    coerce_arg   0.31
       100 :     test_arg   1.84    coerce_arg   1.20
---1000---('1')
        10 :     test_arg   0.10    coerce_arg   0.07
        25 :     test_arg   0.24    coerce_arg   0.17
       100 :     test_arg   0.98    coerce_arg   0.64




More information about the Python-list mailing list