memoize

Creates a version of a function that caches its results.

Category: Software Development Tools > Performance and Memory

Syntax

m = memoize(fun)

Returns a memoized function object for the function handle fun.

Description

Calling m(x) the first time runs fun(x) and stores the inputs and outputs. Calling it again with equal inputs returns the stored output without running fun. This pays off when the same expensive computation is repeated, for example inside a loop or in a recursive definition.

The object has the properties Enabled (turn caching on or off) and CacheSize (how many results are kept, 10 by default), and the helper functions stats and clearCache inspect and reset it. Do not memoize functions whose result depends on random numbers, files or the clock.

Input arguments

fun
Function handle to wrap. It should be deterministic: same inputs, same outputs, no side effects that matter.

Output arguments

m
A matlab.lang.MemoizedFunction object, called like the original function.

Example

Hits and misses

f = memoize(@(x) x^2);
a = f(3)
b = f(3)
s = stats(f);
fprintf('hits %d, misses %d\n', s.Cache.TotalHits, s.Cache.TotalMisses)
Output
a = 9
b = 9
hits 1, misses 1

See also

MemoizedFunction stats clearCache clearAllMemoizedCaches timeit