Basic optimization of python.

metawilm at gmail.com metawilm at gmail.com
Wed Apr 9 07:59:31 EDT 2008


On Apr 7, 7:30 am, "甜瓜" <littlesweetme... at gmail.com> wrote:
> Howdy,
>     I wonder whether python compiler does basic optimizations to .py.
> Eg:
> t = self.a.b
> t.c = ...
> t.d = ...
> .vs.
> self.a.b.c = ...
> self.a.b.d = ...
> which one is more effective? Since each dot invokes a hash table lookup, it
> may be time consuming. If the compiler can do expression folding, then no
> manual folding is needed.

The compiler can not simply do such folding, as just the act of
looking up an attribute can have all kinds of side effects via the
methods __getattr__ and __getattribute__ . So the second time you look
up self.a the value can differ from the first time, or the attribute
may not exist anymore!

> Again, how about contant calculation?
> Eg:
> a = 1 + 2
> .vs.
> a = 3
> which one is more effective? Does the compiler calculate the result at
> compile time? How about constant spreading?

This is safe, and is done:

>>> import dis
>>> def f(): x = 1 + 2
...
>>> dis.dis(f)
  1           0 LOAD_CONST               3 (3)
              3 STORE_FAST               0 (x)
              6 LOAD_CONST               0 (None)
              9 RETURN_VALUE
>>>

- Willem



More information about the Python-list mailing list