2
$\begingroup$

Sometimes I have a cell which takes a while to re-evaluate, but the result is quite small. It would be nice to have an easy way to "cache" some computations by embedding the result in the notebook, and automatically reusing that result on rerun.

IE, instead of

result = expr

I would do

result = memoizedEvaluation[expr]

Any suggestions to how to implement this?

This was motivated by the cell below, result is small, but it takes couple of minutes to evaluate.

graphNamesOrig = Join @@ Table[GraphData[k], {k, 80, 200}]; graphSpectraOrig = N[GraphData[#, "LaplacianSpectrum"]] & /@ graphNamesOrig; 
$\endgroup$
8
  • 1
    $\begingroup$ Do you want it to persist across Mathematica sessions, through kernel restart etc? $\endgroup$ Commented Feb 28, 2023 at 21:01
  • 1
    $\begingroup$ Have you seen Iconize and PersistentSymbol? $\endgroup$ Commented Feb 28, 2023 at 21:19
  • $\begingroup$ Control+Shift+L? $\endgroup$ Commented Feb 28, 2023 at 21:38
  • 1
    $\begingroup$ There is also Once. $\endgroup$ Commented Feb 28, 2023 at 22:06
  • 1
    $\begingroup$ Aha, Once[expr,"Local"] seems to be the thing for this usecase $\endgroup$ Commented Feb 28, 2023 at 22:58

1 Answer 1

3
$\begingroup$

You can check how many PersistentObjects you have already

Length@PersistentObjects["Hashes/Once/*", "Local"] 

Now you can do your slow calculation using Once, here I'm timing using EchoTiming, and the function is RandomReal so very unlikely to repeat the value.

EchoTiming[ key = Once[ CompoundExpression[ Pause[1], Hash[RandomReal[9, 10^7]] ] , "Local" ] ] 

Now you can see that you have more PersistentObjects

Length@PersistentObjects["Hashes/Once/*", "Local"] 

You can now exit the Kernel

Exit[] 

And repeat all the previous actions.

You should observe that subsequent evaluations take much shorter time, and always return the same value, as in the GIF below.

enter image description here

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.