runtime

compare approaches one problem · three ways

Compare Approaches

The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.

Memoising: dict vs lru_cache vs cache

Count ways to climb n stairs taking 1 or 2 steps, without recomputing.

what differs

All three store results by argument. The decorators also give cache_info() and cache_clear(), and are thread-safe. A module-level dict outlives every call, so it's easy to forget to clear.

at a glance

approachuse it when
A · manual dictYou need control over the key or the stored value.
B · @lru_cache(maxsize=128)Many distinct inputs: maxsize bounds memory by evicting the least recently used.
C · @cacheA pure function whose inputs are few enough to keep every result.

Watch out: Arguments must be hashable (no lists). Caching a function with side effects or time-dependent results returns stale answers.

the outputs

Each approach runs on the same input.

concepts

memoizationfunctools.lru_cache

learn it

Caching: remember results instead of recomputing

related comparisons

Wrapper without wraps vs decorator with functools.wraps · Recursion vs iteration

A · manual dict
B · @lru_cache(maxsize=128)
C · @cache
Compare Python Approaches · Runtime