liveBook · Manning

Memoization

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

Memoization is an optimization technique that caches the results of computations so repeated requests for the same inputs can be answered without recomputation.

Memoization caches completed computations so repeated requests for the same inputs return stored results instead of triggering recomputation. It addresses recursive Fibonacci’s repeated subproblems: the naive implementation expands exponentially and becomes impractical even for modest inputs. section 1.1

A Swift implementation develops the technique in small steps:

  • Create a dictionary keyed by the function’s input and prefill known base cases. section 1.1
  • Return a cached value immediately when the input is already present. section 1.1
  • Otherwise compute the result recursively, store it, and return the stored value. section 1.1
  • For Fibonacci, memoization reduces the calls for fib(20) from 21,891 to 39; an iterative solution can be even more performant. section 1.1

Where memoization helps

Memoization suits work whose results are likely to be requested again. Applications include parsers and language runtimes; some Prolog runtimes automatically memoize function calls. section 1.6

var fibMemo: [UInt: UInt] = [0: 0, 1: 1]  // our old base cases
func fib3(n: UInt) -> UInt {
    if let result = fibMemo[n] {  // our new base case
        return result
    } else {
        fibMemo[n] = fib3(n: n - 1) + fib3(n: n - 2)  // memoization
    }
    return fibMemo[n]!
}

Inspect the complete Swift memoized Fibonacci function, including the dictionary, cached lookup, recursive cases, and stored result. section 1.1

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Defines the technique, implements it with a Swift dictionary, measures Fibonacci’s improvement, and contrasts it with iteration.
Examples
Uses recursive Fibonacci, a Swift Dictionary memo table, parser work, and automatic memoization in Prolog runtimes.
What you can do after
Apply it via a Swift Dictionary to cache recursive results and diagnose redundant calls in Fibonacci-like computations.
How it connects
Connects memoization with recursion, iterative algorithms, parsers, and language runtimes.

Also explained in

Compare how 8 books explain memoization →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.