Skip to content

Instantly share code, notes, and snippets.

@danbednarski
Last active April 12, 2025 17:35
Show Gist options
  • Save danbednarski/d35a4b219e83df789547db4586a0286d to your computer and use it in GitHub Desktop.
Save danbednarski/d35a4b219e83df789547db4586a0286d to your computer and use it in GitHub Desktop.
Comparing simple handrolled memoization to @cache decorator from functools
# curiosity piqued by this note: https://substack.com/@pythonclcoding/note/c-107253391
from functools import cache
@cache
def fib_cache(n):
if n <= 1:
return n
return fib_cache(n-1)+fib_cache(n-2)
my_cache = {}
def fib_memo(n):
if n <= 1:
return n
if n in my_cache:
return my_cache[n]
fib_n = fib_memo(n-1)+fib_memo(n-2)
my_cache[n] = fib_n
return fib_n
@danbednarski
Copy link
Author

>>> from test_cache import fib_cache, fib_memo
>>> from timeit import timeit
>>> timeit(lambda: fib_cache(200), number=9001)
0.0011600839789025486
>>> timeit(lambda: fib_memo(200), number=9001)
0.0016002089832909405

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment