# Memoization

> Saving a function's answer for each input. The same call is then instant.

**Field:** Software Development  
**Category:** Algorithms & Data Structures  
**Also known as:** Memoize, Memoisation, functools.cache

## Think of it like

Think of it like a note on the fridge. It holds an answer you already worked out.

## Definition

Memoization means saving what a function gives back for each input. The next call with that input is then instant. The saved answers sit in a table, often a hash table keyed by the input. It is only safe on pure functions, whose answer never changes for the same input. In Python, one line with functools.cache adds it. It is the top-down way to do dynamic programming.

## Example

Lucy adds @functools.cache to her Fibonacci function. fib(50) comes back at once instead of running for hours.

## Example code

```python
import functools

@functools.cache
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

print(fib(50))  # 12586269025
```

Each fib(n) is worked out once, then read from the cache.

## Why it matters

One line can turn a function that never finishes into one that answers at once.

## Common mistake

Memoizing a function that reads the clock or a database. It keeps giving back an old, wrong answer.

## Three principles

- **Save each answer.** Keyed by its input.
- **Pure functions only.** Same input, same answer.
- **Top-down DP.** One kind of dynamic programming.

## Related terms

- [Dynamic Programming](https://learn.benibix.com/term/development/dynamic-programming)
- [Pure Function](https://learn.benibix.com/term/development/pure-function)
- [Hash Table](https://learn.benibix.com/term/development/hash-table)
- [Recursion](https://learn.benibix.com/term/development/recursion)

---

Source: https://learn.benibix.com/term/development/memoization
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-19
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
