DEV Community

qing
qing

Posted on • Edited on

Quick Python Tip: Use functools.cache for Effortless Memoization

Quick Python Tip: Use functools.cache for Effortless Memoization

Memoization is a powerful technique to optimize recursive functions by storing the results of expensive function calls and reusing them when the same inputs occur again. In Python, we can achieve memoization using the @functools.cache decorator. Let's consider the classic Fibonacci sequence example to demonstrate its effectiveness.

Before using @functools.cache:

def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)
Enter fullscreen mode Exit fullscreen mode

This implementation has an exponential time complexity due to the repeated computations.

After applying @functools.cache:

import functools

@functools.cache
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)
Enter fullscreen mode Exit fullscreen mode

With @functools.cache, the Fibonacci function now has a linear time complexity, as the results of previous computations are cached and reused.

Note that @functools.cache is similar to @functools.lru_cache, but the latter has a limited cache size, whereas @functools.cache has an unbounded cache. This makes @functools.cache a better choice when you need to memoize a function with a large input space.

In summary, using @functools.cache is a simple and effective way to optimize recursive functions through memoization, making it a valuable tool to have in your Python toolkit.


Follow me on Dev.to for daily Python tips and quick guides!


💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*


💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*


喜欢这篇文章?关注获取更多Python自动化内容!

Top comments (0)