[Zope-dev] local namespace optimizations?

dieter at handshake.de dieter at handshake.de
Wed Jul 5 16:29:34 EDT 2006


Sidnei da Silva wrote at 2006-7-5 16:45 -0300:
> ...
>It has been demonstrated in other lists that global lookups are most
>of the time faster than local lookups in recent versions of python.

That would extremely surprise me:

  While global lookup was significantly optimized,
  it is still an lookup with a string as argument.

  For local lookup on the other hand, the compiler has
  turned the name into an index and at runtime, an
  indexed access it made. That is still faster.


An a simple test shows that I am right:

>>> i = 1
>>> def f1(): # using global "i" directly
...   x=0
...   for k in xrange(100): x += i
...
>>> def f2(): # using global "i" via local "_i"
...   x=0; _i=i
...   for k in xrange(100): x += _i
...
>>> from timeit import Timer
>>> t=Timer('__main__.f1()', 'import __main__')
>>> t.timeit()
33.647971153259277
>>> t=Timer('__main__.f2()', 'import __main__')
>>> t.timeit()
28.818410873413086



I have seen timings which might be misinterpreted in the way
you described above:

    def f(..., opt1=glob1):
      ...

can be slower than directly using "glob1".
The reason in this case is that handling optional arguments
costs something which might eat the savings due to local access.

>
>
>-- 
>Sidnei da Silva
>Enfold Systems                http://enfoldsystems.com
>Fax +1 832 201 8856     Office +1 713 942 2377 Ext 214

-- 
Dieter


More information about the Zope-Dev mailing list