Python 2 times slower than Perl
Thomas Wouters
thomas at xs4all.net
Wed Jul 18 09:09:10 EDT 2001
On Tue, Jul 17, 2001 at 05:12:23PM -0400, Christopher A. Craig wrote:
> > if you put the code in a function, it will be a fair bit faster
> > since global variable access is slower than local variable access.
> This is, in this case, incorrect. Unless I am horribly mistaken, the
> higher cost of dealing with globals is that you first have to do a
> failed lookup in the local dictionary. (Plus failed lookups are more
> expensive than successful ones)
Nope. The compiler knows, at compiletime, which variables are local, and
compiles the accesses into separate 'LOAD_FAST' ('optimized' local namespace
which is just an array indexed by compile-time constants), 'LOAD_GLOBAL'
(global or builtin namespace lookup, basically one (or two) dictionary
lookups) and 'LOAD_NAME' (code that tries locals, then globals) -- the
latter is only used if the local namespace *might* introduce names by
itself, because of an 'import *' or bare 'exec'.
As a result, function namespaces (which we call 'local') are faster than
global namespaces (which can be the 'local' namespace for a statement, but
we don't really *call* a 'local' namespace, because we mean the optimized
'local' namespace in functions when we say 'local namespace'.)
> In this particular case the local dictionary is the same as the global
> one, so I don't see how moving to a function would offer a time savings.
Yes, it is, but if you refactor, the local namespace won't be a dictionary
any more, so it'll be faster :)
--
Thomas Wouters <thomas at xs4all.net>
Hi! I'm a .signature virus! copy me into your .signature file to help me spread!
More information about the Python-list
mailing list