functools.lru_cacheis a built-in Python decorator that brings memoization to your functions.It speeds up your code by caching (storing) the results of expensive function calls, so that when the function is called again with the exact same arguments, Python skips the calculations entirely and immediately pulls the result from memory.
The LRU stands for Least Recently Used. This means the cache has a size limit, and once it fills up, Python automatically discards the oldest, least-used entries to keep your memory clean.
from functools import lru_cache
import time
# 1. Apply the cache wrapper (limiting size to the 128 most recent calls)
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
# 2. Test performance
start = time.perf_counter()
result = fibonacci(35)
end = time.perf_counter()
print(f"Result: {result}")
print(f"Execution Time: {end - start:.6f} seconds")
The Performance Difference:
• Without @lru_cache: Calculating fibonacci(35) takes around 2 to 5 seconds and millions of function calls.
• With @lru_cache: It takes around 0.00005 seconds and exactly 36 function calls.