I am trying to evaluate a function, which has simplified form as below.

f[a_] := 5*a

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

Table[ParallelTable[X[a, b], {b, 1, 6400}], {a, 1, 40}]

Now, my problem is that for 6400 runs over "b", f[a] is calculated every time, in spite of being put under the module. This is what, I want to avoid as for all the runs over 'b', f[a] to remain same. I am not able to figure out how to achieve this. Will appreciate any help.

  • 1
    $\begingroup$ try ClearAll[X];X[a_, b_]:=Module[{A= f[a], g[b] = 6*b}, A + g[b]];? $\endgroup$
    – kglr
    Commented Feb 5, 2021 at 12:52
  • $\begingroup$ ParallelTable[5 a + 6 b, {b, 1, 6400}, {a, 1, 40}] ? Seems there are only simple calculation? $\endgroup$ Commented Feb 5, 2021 at 12:53

2 Answers 2


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:


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.


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).

  • 2
    $\begingroup$ f[a_]:=f[a] thing worked. I could not figure it out in three days !! Thanks by the way. $\endgroup$
    – user49535
    Commented Feb 5, 2021 at 16:57
  • $\begingroup$ You are welcome :) $\endgroup$ Commented Feb 5, 2021 at 17:38
  • 1
    $\begingroup$ This is called memoization, just to clarify what the method is that is being used. $\endgroup$ Commented Feb 6, 2021 at 19:14
  • $\begingroup$ I should actually add that in, I had forgotten the name of it $\endgroup$ Commented Feb 6, 2021 at 19:55

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 !


Not the answer you're looking for? Browse other questions tagged or ask your own question.