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$
    – Kuba
    Feb 28 at 21:01
  • 1
    $\begingroup$ Have you seen Iconize and PersistentSymbol? $\endgroup$
    – Michael E2
    Feb 28 at 21:19
  • $\begingroup$ Control+Shift+L? $\endgroup$
    – mikado
    Feb 28 at 21:38
  • $\begingroup$ There is also Once. $\endgroup$
    – Jason B.
    Feb 28 at 22:06
  • 1
    $\begingroup$ Aha, Once[expr,"Local"] seems to be the thing for this usecase $\endgroup$ Feb 28 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$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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