How to make a function store data to avoid repeating computation

You could redefine f. It looks a bit better and can be seen as a “Julia thing”.

julia> function f()
           global _output = (println("heavy calculations"); 12)
           @eval f() = _output
           return _output
       end
f (generic function with 1 method)

julia> f()
heavy calculations
12

julia> f()
12

More generally, it seems you want to emulate the behaviour of local static variables from C/C++. There are multiple requests for such feature (see this issue).

2 Likes