How to avoid repeated calculation of a function

I am not sure if this is what you are looking for, but this may help. You can use memoization to define f such that every time it is evaluated, it stores the value in memory:

f[a_]:=f[a]=5*a

Now if you call f[3] twice, the first time he will compute 5*3 = 15, and the second time he will retrieve the value he has in memory and return 15.

I would also ditch the Module, as Mathematica is not very good at deleting old variables and this may end up eating all your ram.

Try:

X[a_,b_]:=With[{A=f[a], g[b]=6*b},A + g[b]]

(I suppose you don't need this if you follow my initial advice but in general, it is good practice to use With instead of Module).


Change the definition X[a_,b_] to

X[a_, b_] := Module[{A = f[a], g = Function[b, 6 b]}, A + g[b]];
X[a,b] (*5 a + 6 b*)

That's it !