Definition
Memoization is storing each function call’s result, keyed by the call’s arguments, so that a later call with the same arguments returns the stored result instead of recomputing it. Caching is the general practice of keeping a computed or fetched result where it is quicker to reach; memoization is caching of function results. The difference that matters is the key: memoization keys by arguments alone, which is correct only for a function that reads nothing else; a general cache needs a key covering everything its result depends on.
The idea
The Fibonacci numbers show the gain. Each is the sum of the two before it: , and . Computed straight from this definition, takes 2,692,537 calls, because smaller values are recomputed again and again: twice, three times, five times. With memoization each of the 31 values to is computed once, in 59 calls. Systems gain in the same way when a file is parsed once, a name looked up once, or a program checked once and the verdict reused.
A stored result is a conclusion drawn from premises, the facts the computation read. Reusing it is valid while every premise still holds. The key records the premises that vary between calls; every premise not in the key must be kept unchanged by other means. A pure function, one whose result depends only on its arguments and which changes nothing else, has its arguments as its only premises, so its stored results never go stale, meaning out of date. A parse, a lookup or a verification usually also reads the parser’s version, a table’s contents or the checker’s rules. Each such premise must be in the key, or a change to it must remove the results that relied on it.
How it works
A memoized or cached computation has these parts.
The computation : the expensive work being saved.
The key: a value built from everything the result depends on that can differ from one call to the next.
The table: a store from keys to results, usually a hash table §14.7, which finds the entry for a key in a few steps on average.
The eviction policy: the rule that chooses which entry to discard when the table is full, for example LRU (least recently used), which discards the entry unused for the longest time.
The validity rule: how the cache learns that a premise outside the key has changed.
A lookup goes as follows.
Build the key from the arguments and from every other premise the result depends on, such as a version number.
Look the key up in the table. If an entry is found, compare its stored key with the new key in full; on a match, return the stored result. This is a hit.
Otherwise, on a miss, compute the result, store it under the key, evicting an entry first if the table is full, and return the result.
A premise that can change is handled in one of two ways. The first puts a version number of the premise into the key: a change increases the number, old entries never match again, and eviction removes them later. The second keeps the premise out of the key and, on each change, deletes every entry that relied on that premise; the cache invalidation §14.21 entry treats this. Discarding entries after a fixed time, a third practice, bounds how long a stale result can be served but does not prevent it.
Worked example
Memoized . Every computed value, and included, is stored. calls , which calls , which calls , which calls and ; then is stored. Back in , the second call, , is a hit, so . In , the second call, , is a hit: . In , the second call, , is a hit: . That is 9 calls: 6 computations and 3 hits. Without memoization, let be the number of calls needed for . Then and , so , , and .
A key that misses a premise. A checker examines programs before they run. One program calls a library routine fill and passes it a 16-byte buffer. Version 1 of the library documents that fill writes at most 8 bytes, so the checker accepts the call, since , and stores the verdict accept under a key computed from the program’s bytes alone. Version 2 of the library changes fill to write up to 32 bytes. The program’s bytes are unchanged, so its key is unchanged, and the next check is a hit that returns accept. The correct verdict is now reject: the call can write bytes past the end of the buffer.
The repair adds the library’s contract to the key, as the library’s version number or as a cryptographic hash §5.1 (a fixed-length fingerprint that, in practice, differs whenever the data differs) of the contract text. With version 2 the key differs, the lookup misses, and the checker recomputes and rejects. No hash of the program’s bytes, however strong, could have caught the change, because the changed premise was not among the hashed bytes.
Stated precisely
Write the computation as , where is the explicit input (the arguments); is the context, meaning every other value the computation reads, such as code versions, configuration, stored data, the contracts of routines it calls and the time; and is the result. A cache entry holds a key and the result computed when the entry was stored. A later lookup with input in context that produces the same key returns . That reuse is correct when .
A cache returns only correct results when the key determines the result: for all inputs and contexts, implies . Three conditions give this.
Determinism. gives the same result whenever and are the same; it reads no clock, random number or other value that does not include.
Coverage. Every part of that can affect the result is in the key, or is guaranteed not to change while the entry exists; invalidation provides that guarantee.
Exact comparison. Keys are compared in full, or through a collision-resistant §5.5 cryptographic hash, one for which finding two different inputs with the same hash is infeasible. The short hash a hash table uses is not enough on its own, because two different keys can share it.
For a pure function, is empty, the arguments are the whole key, and entries never go stale. Eviction never breaks correctness, because a discarded entry is simply recomputed; keeping an entry whose premises have changed does break it.
Resolving a lookup once
A common systems form of memoization resolves a lookup by name once and keeps the result. Take a program that, for every incoming event, finds five tables by name: it formats a name string such as limits:conn42 and looks the string up in a hash table, which means building the string, hashing it (computing a number from its characters) and comparing it with stored names. The set of tables changes only when a new configuration is loaded. So the program can look up all five names once, at loading time, and store the five resulting pointers (memory addresses) in a small structure, called here a resolved view. Each event then follows a pointer directly.
The resolved view holds memoized lookup results whose hidden premise is the configuration they were resolved against. It costs its own size for each configuration alive at the same time: with 4-byte pointers, five pointers take bytes, plus any bookkeeping the memory allocator adds. During a switch the old and the new configuration are both alive, so two views exist for a while.
The view must be replaced together with the tables it points into, as one unit. If the tables are replaced and freed while the old view is kept, the view points to freed memory, a use-after-free §4.6. If the view is replaced before the new tables are ready, readers follow pointers to tables that do not exist yet. The standard pattern puts the tables and their view in one structure and publishes a new structure by changing a single pointer with an atomic operation §9.8, one that other threads see either not at all or completely. The old structure is freed only after every reader that might still use it has finished, a wait called a grace period §9.21 in read-copy update §9.20 (RCU).
Limits and common mistakes
Memory grows with every distinct key. A cache keyed by input that an attacker chooses, with no eviction policy and no bound on the number of entries, lets the attacker fill memory.
Hits are faster than misses, so the time a request takes can reveal whether the same request was made recently. That is a side channel §1.29: information leaking through a measurable effect other than the output.
A time limit on an entry bounds how long a stale result is served; it does not make the result correct during that time. A known change must remove the entries that depend on it at once.
Memoizing a function that has side effects, such as writing a log or sending a message, skips those effects on every hit. A table that hands out the stored object itself, instead of a copy, lets one caller’s change to that object reach every later hit.
Two threads that miss on the same key at the same time compute the result twice, which for a deterministic only wastes time. A worse race stores a stale result: a thread computes from old data, the data changes and the dependent entries are deleted, and then the thread stores its old result. Recording the data’s version when the computation starts, and storing only if that version is still current, prevents this.
Questions answered
What changes invalidate a cached parse, lookup, or proof?
A cached parse, lookup or proof becomes invalid when anything the result depended on changes and that thing is not part of the cache key, the value used to find the stored result. A key that includes the changed item turns the change into a miss automatically; every other change must be matched by deleting the entries that relied on it. The usual dependencies are these.
Parse: the input bytes; the parser’s version and grammar; options such as character encoding, size limits or format version.
Lookup: the contents of the table, through an entry added, removed or changed; what the name refers to, since a file or object can be replaced while its name stays the same; the access rights that decide whether the caller may see the entry.
Proof, meaning a stored verdict that something is safe or allowed: the checked object’s bytes; the checker’s version and rules; the contract of every routine the object relies on, such as how many bytes a called routine may write; and the environment the verdict assumed, such as memory sizes, configuration, trusted keys and the security policy.
A change to something the result does not depend on invalidates nothing. Concluding that a result does not depend on something requires a complete record of what the result read; when that record may be incomplete, discarding all entries is safe, because a discarded entry costs only the time to compute it again.
Related entries: Graph reachability search (§14.18), Cache invalidation (§14.21), Security claim scope (§1.45).