Simple question about how the optimizer works

Simon Brunning SBrunning at trisystems.co.uk
Thu May 9 05:58:39 EDT 2002


> From:	jb [SMTP:jblazi at hotmail.com]
> > Let us assume, f(x) is a relatively complicated function and g(x,y) and
> > h(x,y) are functions.
> > 
> > How often is then f called in the following code:
> > 
> > print g(f(x),f(x))
> > print h(f(x),f(x))
> > 
> > I think this topic is called "common subexppression elimination" in
> > computer science.
> > 
> > TIA,
> 
> That was a dumb question, sorry. So I have tried and I am a bit surprised 
> that f is called four times! 
> Why?
 
'Cuz *you* called it four times, that's why. If you want f() called only
once, re-code as:

spam = f(x)
print g(spam, spam)
print h(spam, spam)

I can't see how this optimisation could be automated - function f may or may
not have side effects. (Python isn't a functional language, after all.) If
it does, the programmer may or may not want these side effects to occur
multiple times. So just code it the way you want it!

Cheers,
Simon Brunning
TriSystems Ltd.
sbrunning at trisystems.co.uk




-----------------------------------------------------------------------
The information in this email is confidential and may be legally privileged.
It is intended solely for the addressee. Access to this email by anyone else
is unauthorised. If you are not the intended recipient, any disclosure,
copying, distribution, or any action taken or omitted to be taken in
reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot
accept liability for statements made which are clearly the senders own.





More information about the Python-list mailing list