Assigning to None (was Re: Question about Python)

Bengt Richter bokr at oz.net
Sun Jul 3 15:19:05 EDT 2005


On Sun, 03 Jul 2005 11:47:07 +1000, Steven D'Aprano <steve at REMOVETHIScyber.com.au> wrote:

>On Fri, 01 Jul 2005 12:59:20 -0400, François Pinard wrote:
>
>> [Peter Hansen]
>>> Mike Meyer wrote:
>>> > Yes. I once grabbed an old program that did assignments to None. But
>>> > that's always been a bad idea.
>> 
>>> What was the use case!?
>> 
>> People used to assign None to itself as a keyword argument in function
>> headers.  The goal was to make a local copy of the reference, which was
>> then accessed faster than the global thing.
>
>Can you say "premature optimization is the root of all evil"?
>
>I'd like to see the profiling that demonstrated that this made a
>significant -- or even measurable -- speed-up in anything but the most
>unusual cases.
>
The difference between local and global access is definitely measurable, though
there's no reason to use None as the local name if you want to do that kind
of optimization (not possible in 2.4+)

 >>> from time import clock
 >>> def test():
 ...     none = None # local
 ...     t0 = clock()
 ...     for i in xrange(10**6): v = None
 ...     t1 = clock()
 ...     for i in xrange(10**6): v = none
 ...     t2 = clock()
 ...     print 't1-t0 = %f, t2=t1 = %f, ratio = %f' %(t1-t0, t2-t1, (t1-t0)/(t2-t1))
 ...
 >>> test()
 t1-t0 = 0.971914, t2=t1 = 0.766901, ratio = 1.267327

about 25% longer to get a global (AND bind it locally, which the two timings share)
than to do the same for a local, it seems.

Regards,
Bengt Richter



More information about the Python-list mailing list