rewrite for achieving speedup

Alex Martelli aleax at mac.com
Tue Apr 17 21:48:30 EDT 2007


Jun.Jin.act+group.python at gmail.com <Jun.Jin.act at gmail.com> wrote:

> why would binding to a function-local name speeds up performance?

Like any other constant-hoisting, pulling the lookup out of the loop
speeds things up because otherwise Python must repeat the lookup each
time through the loop (Python doesn't _know_ that, for example, zip.zap
is always the same bound method object -- without potentially deep
analysis, it can't rule out that looking up zap on zip has side effects
and the like, so when you tell it to look it up, it looks it up, no ifs,
no buts).

You can measure the effect with -mtimeit ...:

brain:~ alex$ python -mtimeit -s'def f(L):
>  for x in xrange(1000): L.append' 'f([])'
1000 loops, best of 3: 215 usec per loop

brain:~ alex$ python -mtimeit -s'def g(L):
>   ap = L.append
>   for x in xrange(1000): ap' 'g([])'
10000 loops, best of 3: 79.1 usec per loop

note that in each function f and g I'm doing only the lookup, not the
call to the method thus looked up.

Of course, this depends on the fact that for a function to use a local
variable takes very little time indeed (since the compiler identifies
which variables are local, and transforms any use of their names into a
rapid indexing of a "local variables array", at the time the def
statement executes -- so by the time the function gets called, i.e.,
that its body executes, that execution takes advantage of this
optimization automatically performed by the Python compiler).


Alex



More information about the Python-list mailing list