subexpressions

Diez B. Roggisch deets at nospam.web.de
Fri Jun 1 09:04:23 EDT 2007


> Ok, I stand corrected.
> 
> Duplicate subexpressions are pretty easy to avoid in
> Python, so though an optimization would not be
> impossible here (checking for immutability of
> builtins, etc., which still assumes the idea that
> multiplication is more expensive than checking for
> immutability even for the common builtin case), it
> would not be worthwhile.
> 
> Shortly after I posted, there was an elegant solution
> to avoiding having to repeat x*x in the lambda, so the
> point's kind of moot now.

The elegance of that solution very much depends on the cost of the duplicate
operation vs. the additional function call.

And for the usecase at hand, that's exactly the point not to do it:

droggisch at ganesha:/tmp$ python -m timeit '(lambda x: lambda y: y+y)(10 *
10)'
1000000 loops, best of 3: 1.04 usec per loop
droggisch at ganesha:/tmp$ python -m timeit 'lambda: 10 * 10 + 10 * 10'
1000000 loops, best of 3: 0.336 usec per loop


Diez



More information about the Python-list mailing list