liveBook · Manning

Memoization

As explained in Clojure: The Essential Reference

Memoization is a caching technique that stores the results of function evaluations keyed by their inputs.

Memoization wraps a function with a cache keyed by its complete argument list. Repeated calls return the stored result without recomputation, while preserving the function's public interface. section 2.4.2

Use memoization when:

  • The computation is expensive, accepts values with a small memory footprint, and receives a finite or estimable set of repeated inputs. section 2.4.2
  • The wrapped function must accept variable arity; supply a callable function, or expect ClassCastException and missing-argument ArityException. section 2.4.2

Cache misses happen once per argument list

(defn- f* [a b] (println (format "Cache miss for [%s %s]" a b)) (+ a b)) (def f (memoize f*)) (f 1 2) ; prints a miss, returns 3 (f 1 2) ; returns 3 without printing (f 1 3) ; prints a miss, returns 4

How Clojure: The Essential Reference covers it

How deep it goes
Defines the function contract, demonstrates cache hits, and instruments calls, hits, misses, and estimated memory.
Examples
Uses memoized addition, Levenshtein distance, dictionary filtering, spelling suggestions, and cache statistics.
What it assumes
Assumes a callable function and argument-based evaluation, while defining required input, output, arity, and exception behavior.
What you can do after
Apply it via Clojure's memoize to eliminate repeated computation and inspect behavior with a custom instrumented wrapper.
How it connects
Connects caching, function wrappers, function generation, performance, and Levenshtein distance.

Also explained in

Compare how 8 books explain memoization →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.