Strategy: Use memoization and then save the relevant definition in a file at the end of your session. Next session you can recover the "memoized" definition.
Memoization
Look at memoization also on other questions, particularly 2639. You can do this
f[x_]:=f[x]=ExpensiveFunctionOf[x]
You can then call f[x]
and ExpensiveFunctionOf
is evaluated only if the parameter x
is different from previous evaluations. Otherwise, Mathematica will remember the output value from previous evaluations.
For example, notice how the first time f[10]
is evaluated it takes 5 seconds (Pause[5]
) but the second time is instantaneous because the definition of f
now includes a specific entry for f[10]
with the output of ExpensiveFunctionOf[10]
as DownValues
.
ClearAll[f,ExpensiveFunctionOf];
ExpensiveFunctionOf[x_]:=(Pause[5];Factorial[Round[x]])
f[x_]:=f[x]=ExpensiveFunctionOf[x]
AbsoluteTiming[f[10]]
(* {5.00058,3628800} *)
AbsoluteTiming[f[10]]
(* {0.00002,3628800} *)
?f

DumpSave
Then, as suggested by @UlrichNeumann, you can save those definitions using DumpSave
and recover them using Get
DumpSave["f.mx", f]
Get
Get["f.mx"]

DumpSave
in the documentation. $\endgroup$PersistentSymbol["symbol", "Notebook"]
to create a variable that gets saved into a notebook to make it persist between sessions. $\endgroup$PersistentSymbol["symbol", "Notebook"]
is not available in Wolfram Cloud or Wolfram Engine for me to test a complete solution based on that. Do you mind giving an example of how to use it to store the definitions of memoized functions? $\endgroup$PersistentSymbol
is just a variable. If you want to memoize function evaluations, you should useOnce
with the desired persistance location specified. Also take a look atPersistenceLocation
to see what options you have for storing the values. $\endgroup$