optimization with the "compiler" module
Skip Montanaro
skip at pobox.com
Tue Apr 16 21:11:20 EDT 2002
Andrew> Suppose you have
Andrew> class Strange:
Andrew> def __add__(self, other):
Andrew> return self
Andrew> x = Strange()
Andrew> Then x+3+7.0 = (x+3)+7.0 = x+7.0 = x
Andrew> The compiler can't know what 'x' might be so can't fold
Andrew> constants in this case. You could if it was '3+7.0+x'.
This is a trivial peephole optimization. If two constants are summed, they
will appear in the bytecode like
LOAD_CONST 3
LOAD_CONST 7.0
BINARY_ADD
You recognize the pattern, perform the optimization, and move on.
In your example, it would look like
LOAD_GLOBAL x
LOAD_CONST 3
BINARY_ADD
LOAD_CONST 7.0
BINARY_ADD
The pattern (const, const, add) never turns up in the instruction stream.
Details here:
http://manatee.mojam.com/~skip/python/spam7/optimizer.html
Skip
More information about the Python-list
mailing list