Recommended way to cache results of expensive functions?

Shuhua
Sun, 14 Feb 2021 03:04:06 +0000
General Usage

Suppose that I have a function f: Int --> Float64 that conducts some expensive computation, but the integer inputs into f typically have only a very small number of possible values. I thus want to cache the results for speedup. In languages like C/C++, we may use a local static variable. What is the Julian way to do this? A relevant topic is Caching the results of a factory method.

A straightforward method is to define a cache global variable in the enclosing module shown below.

module M

const cache = Dict{Int, Float64}()

function f(a::Int)
  if a ∉ keys(cache)
    # computate and store result in cache[a]
  end
  return cache[a]
end

end

However, if there are multiple functions that need cache, then there will be quite a few global variables like cache1, cache2 that seem a little messy.

7 posts - 5 participants