Monday, March 14, 2011

Local Variable Performance & dis

Local variables are faster in python.  They are accessed as offsets from a stack, rather than looked up in a hashmap.

Here is an example showing the use of local variables as a performance optimization.  http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Local_Variables

Using the dis module, we can investigate this behavior.  Note LOAD_FAST versus LOAD_DEREF.

>>> import dis
>>> def foo():
...   a = 1
...   def bar():
...      return a
...   return bar
...
>>> b = foo()
>>> dis.dis(b)
  4           0 LOAD_DEREF               0 (a)
              3 RETURN_VALUE
>>> def loc():
...    a = 1
...    return a
...
>>> dis.dis(loc)
  2           0 LOAD_CONST               1 (1)
              3 STORE_FAST               0 (a)


  3           6 LOAD_FAST                0 (a)
              9 RETURN_VALUE

No comments:

Post a Comment