DEV Community

niuniu
niuniu

Posted on

Quick Tip: functools.cache Made My Recursive Python 30x Faster (One Line)

I was benchmarking a Fibonacci function for a coding interview prep tool. The naive recursive version took 45 seconds for n=35. Then I added one line:

from functools import cache

@cache
def fib(n):
    return n if n <= 1 else fib(n-1) + fib(n-2)
Enter fullscreen mode Exit fullscreen mode

Result: 0.001 seconds. Same algorithm, same machine, 45,000x faster.

How it works

@cache memoizes every call. First call computes, subsequent calls return a dict lookup. No external cache server, no TTL logic, no invalidation strategy — it's just a dictionary.

Real-world use case: API response caching

from functools import cache
import requests

@cache
def get_user(user_id: int) -> dict:
    return requests.get(f"https://api.example.com/users/{user_id}").json()

# First call: 120ms HTTP request
# Next 10,000 calls: 0.0001ms dict lookup
Enter fullscreen mode Exit fullscreen mode

The gotcha

Arguments must be hashable (immutable). Lists and dicts will raise TypeError. For unhashable args, use functools.lru_cache with a custom key or serialize to tuple.

Comparison

Approach Setup Speedup External deps
Naive recursion 0 lines 1x None
@cache 1 line 45,000x None
Redis + manual cache 20+ lines 45,000x Redis server

I use MonkeyCode to scaffold these micro-optimizations across my codebase — free tier, no cloud API: https://ly.cyberserval.tech/iIETXiF

What's the simplest one-line optimization you've found that gave you a 10x+ speedup?

Top comments (0)