36. Caching data and results

The key here is to use the lru_cache decorator to cache results of functions that are idempotent, especially if they are expensive to call. Note how calls to add takes about 700 milliseconds? However, using the lru_cache decorator, subsequent calls are on the order of microseconds.

36.1. Don’t do this

1def add(n):
2    return sum([i for i in range(n)])
3
4add(10000000)

36.2. Do this

1from functools import lru_cache
2
3@lru_cache(maxsize=32)
4def add(n):
5    return sum([i for i in range(n)])
6
7add(10000000)