Use cases for del

Scott David Daniels Scott.Daniels at Acm.Org
Fri Jul 8 17:21:53 CEST 2005


Ron Adam wrote:
> Here's something interesting:
> 
> import time
> 
> x = None
> t = time.time()
> for i in range(1000000):
>     if x==None:
>         pass
> print 'None:',time.time()-t
> 
> x = 'to-end'
> t = time.time()
> for i in range(1000000):
>     if x=='to-end':
>         pass
> print 'String:',time.time()-t
> 
>  >>>
> None: 0.46799993515
> String: 0.360000133514
> 
> 
> Of course the difference this would make on a single call in practically 
> Nill.
> 
> Anyway, time to call it a night so tomorrow I don't make anymore silly 
> mistakes on comp.lang.python. :)
> 
> Cheers,
> Ron
> 

Try this:
import time
def timed(number):
     nreps = ereps = [None] * number
     t0 = time.time()
     x = None
     for i in ereps:
         if x == None:
             pass
     x = 'to-' + 'end' # make sure equal string, not identical string
     for i in nreps:
         if x == None:
             pass
     t1 = time.time()
     for i in ereps:
         if x == 'to-end':
             pass
     x = None
     for i in nreps:
         if x == 'to-end':
             pass
     t2 = time.time()
     x = None
     for i in ereps:
         if x is None:
             pass
     x = 'to-end'  # magic unnecessary here.
     for i in nreps:
         if x is None: pass
     return t0, t1, t2, time.time()

t0, t1, t2, t3 = timed(1000000)
print '== None:', t1 - t0
print '== String:', t2 - t1
print 'is None:', t3 - t2
===========================
== None: 0.578000068665
== String: 0.594000101089
is None: 0.31200003624

Testing for None should be an is-test (not just for speed). In
older pythons the == result wasn't necessarily same as is-test.
This made sense to me after figuring out NULL in database stuff.
is-test will always work for None despite the other half.  Not
so for bogus objects like:

 >>> class WildCard(object):
         def __eq__(self, other):
             return True

 >>> (WildCard() is None), (None is WildCard())
(False, False)
 >>> (WildCard() == None), (None == WildCard())
(True, True)

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list