Write a Function That Remembers Computed Values

Storing the results of a computationmemoizationcan speed up a function that is called repeatedly with the same arguments, at a cost of greater memory usage.

Start with a function definition

Here is a function that returns the Korean name of an integer:

Repeated calls to the function with the same argument take about the same amount of time:

Make the function remember previously computed values

Use this idiom to make a function remember previously computed values (to memoize the function):

Apply that idiom to the integerInKorean function:

The first invocation of the memoized function with a particular argument takes about the same amount of time as the unmemoized function:

Subsequent invocations with the same argument are much faster because the function retrieves the previously computed result rather than computing it from scratch. In this case, the function executes nearly 200 times faster:

See a list of remembered values

Call integerInKorean with a few more values:

See the remembered values using ?(Information):

Delete the remembered values

Delete the remembered values as well as the function definition:

The symbol no longer has any definitions associated with it, and the memory it used has been reclaimed:

Notes
Before changing the definition of a memoized function, you should first Clear the function to remove remembered values, which may be incompatible with the new definition.
Memoization is commonly used to speed up recursive functions.