Memoization is an optimization technique that speeds up programs by the results of previous function calls. This allows subsequent calls to reuse the cached results, avoiding time-consuming recalculation. Memoization caching Memoization is commonly used in , where problems can be broken down into simpler sub-problems. One such dynamic programming problem is calculating the th Fibonacci number. dynamic programming n Fibonacci The are a sequence of integers where each number is the sum of the two preceding numbers, starting with the numbers 0 and 1. Fibonacci numbers = = = F(n - ) + F(n - ) F ( ) 0 0 F ( ) 1 1 F (n) 1 2 A function that calculates the th Fibonacci number is often implemented . n recursively n <= : n fibonacci(n - ) + fibonacci(n - ) : def fibonacci (n) if 1 return return 1 2 The function calls of can be visualized with a recursion tree. fibonacci(4) Notice that the function is called with the same input multiple times. Particularly is calculated from scratch twice. As the input increases, the running time grows exponentially. This is suboptimal and can be improved significantly using memoization. fibonacci(2) Memoization in Python Python 3 makes it incredibly easy to memorize functions. The module included in Python's standard library provides two useful decorators for memoization: (new in Python 3.2) and (new in Python 3.9). These decorators use a cache, which stores items in order of use, discarding the least recently used items to make room for new items. functools lru_cache cache least recently used (LRU) To avoid costly repeated function calls, can be wrapped by , which saves values that have already been calculated. The size limit of can be specified with , which has a default value of 128. fibonacci lru_cache lru_cache maxsize functools lru_cache n <= : n fibonacci(n - ) + fibonacci(n - ) from import @lru_cache(maxsize=64) : def fibonacci (n) if 1 return return 1 2 Now the recursion tree for does not have any nodes that occur more than twice. The running time now grows linearly, which is much faster than exponential growth. fibonacci(4) The decorator is equivalent to . cache lru_cache(maxsize=None) functools cache n <= : n fibonacci(n - ) + fibonacci(n - ) from import @cache : def fibonacci (n) if 1 return return 1 2 Since it does not need to discard least recently used items, is both smaller and faster than with a size limit. cache lru_cache Conclusion Memoization improves performance by caching the results of function calls and returning the cached result when the function is called with the same input(s) again. Python 3 makes it easy to implement memoization. Simply import or from and apply the decorator. lru_cache cache functools