[Tutor] Style question with classes and modules

Kent Johnson kent37 at tds.net
Thu Jul 19 23:51:33 CEST 2007


Terry Carroll wrote:
> On Thu, 19 Jul 2007, Kent Johnson wrote:
> 
>> Attribute lookup seems to have gotten better since Beazley wrote; here
>> is a test program that uses three ways to access math.sqrt - module
>> attribute, global name, local name. Note that in the third version, all
>> three names (sqrt, d, i) are local:
>  . . .
>> Sample output:
>> 745.465993881
>> 561.167001724
>> 369.343996048
> 
> I'm surprised the difference between the second and third versions is so 
> dramatic.  I get a result consistent with that (although you obviously 
> have a much faster CPU than I!).
> 
> Why is that so much faster?  A smaller namespace to look through?  Or the 
> search being short-cut by finding in in the local space and therefore not 
> needing to search the global?  Something else?

Two reasons, IIUC:
- the search is short-cut by finding the name in the local space.
- I'm pretty sure that local names are allocated in an *array* on the 
call stack, not in a dict, so access to local names is very fast - just 
a fixed offset into an array, no hashing and other overhead of 
dictionary lookup.

This is such a common optimization that Raymond Hettinger (the king of 
speed :-) wrote a decorator to do it automatically:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940

Kent



More information about the Tutor mailing list