How to make a function store data to avoid repeating computation

natema
Fri, 07 Oct 2022 11:45:50 +0000
General Usage

I have a function in a module that performs some heavy computation to produce a fixed output.
It is hard to predict if the function will be called, and we want to avoid computing it if unnecessary.
So, we would like the function to be lazy and to store its output the first time it is called.
Here’s one way to do that:

function f()
     isdefined(@__MODULE__, :_output) && return _output
     global _output = ... heavy calculations ...
     return _output
 end

Is it the best and/or most julionic way to do that?

46 posts - 14 participants