memoise a function in r

Memoization is a technique used to improve the performance of functions in R by caching their results. This is done by adding a caching layer to a function that saves the results of computationally expensive operations and returns the cached result on subsequent calls to the same inputs.

Here's an example of memoizing a function that calculates the Fibonacci sequence:

main.r
fib <- memoise(function(n) {
  if (n <= 1) {
    return(n)
  } else {
    return(fib(n-1) + fib(n-2))
  }
})
109 chars
8 lines

The memoise() function from the memoise package is used to wrap the fib() function. The memoized function is then assigned to the fib variable.

Now, whenever fib() is called with a particular argument, the result is cached in memory. If fib() is called again with the same argument, the cached result is returned immediately instead of recalculating the result.

Memoization is a useful technique to speed up functions that are called repeatedly with the same inputs. It's important to note, however, that memoization should only be used when the function's output is solely dependent on its input arguments. If the function's output depends on any external factors, such as the global state, then memoization may result in incorrect results.

gistlibby LogSnag