Adding @cache to Python's Recursive Fibonacci Cuts Runtime From Seconds to Microseconds
A developer demonstrated how Python's memoization decorator, @cache, can dramatically speed up a recursive function by storing previously computed results. The naive Fibonacci function took about 6 seconds to compute fib(40), while the cached version finished in roughly 4 microseconds. The same technique was applied to a grid path-counting problem, which also showed large speedups. The article notes that @cache requires Python 3.9 or later, with @lru_cache as an alternative for older versions. It also cautions that caching suits only pure functions with hashable arguments and can consume memory, with very deep recursion still a risk.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in