From: S. B. Gray on
Suppose I have an expression like

foo =(expression 1)/denominator + (expression 2)/denominator

where "denominator" is itself a complex expression. Is it worthwhile for
me to compute "denominator" once and use it explicitly in foo, or will
Mathematica cleverly deduce that it needs to be computed only once?

My guess is that Mathematica is an interpreter so it will not optimize the code.

Steve Gray

From: M.Roellig on
Hi,

Instead of writing

foo =(expression 1)/(obscenely complex expression )+ (expression 2)/
(obscenely complex expression )

it pays out to do something like :

denominator = obscenely complex expression ;

foo=(expression 1)/denominator + (expression 2)/denominator

Mathematica will calculate the complex expression once and store the
result in denominator
and only use that for later occurances of denominator.

If you use

denominator := obscenely complex expression ;

instead, it will recalculate the complex stuff each time denominator
is encountered.

Markus


>
> foo =(expression 1)/denominator + (expression 2)/denominator
>
> where "denominator" is itself a complex expression. Is it worthwhile for
> me to compute "denominator" once and use it explicitly in foo, or will
> Mathematica cleverly deduce that it needs to be computed only once?
>
> My guess is that Mathematica is an interpreter so it will not optimize the code.
>
> Steve Gray

From: David Bailey on
S. B. Gray wrote:
> Suppose I have an expression like
>
> foo =(expression 1)/denominator + (expression 2)/denominator
>
> where "denominator" is itself a complex expression. Is it worthwhile for
> me to compute "denominator" once and use it explicitly in foo, or will
> Mathematica cleverly deduce that it needs to be computed only once?
>
> My guess is that Mathematica is an interpreter so it will not optimize the code.
>
> Steve Gray
>
A good way to check if an expression is evaluated once or several times,
is to write a debugging function such as:

In[6]:= SetAttributes[xprint, HoldFirst];
xprint[x_] := Module[{ans = x},
Print[Unevaluated[x], "=", ans];
ans
];

In[8]:= xprint[2 + 2]

During evaluation of In[8]:= 2+2=4

Out[8]= 4

Note that this function returns the value of its argument, so it can be
inserted into any expression. Functions like this also has more general
use in debugging code.

David Bailey
http://www.dbaileyconsultancy.co.uk