- In this directory it holds the implementation of cache Decorator in python.
- We can use this decorator when we are using more computational power on stuff that has already been done.
-
Cache Decorator is a default Decorator in python from the built-in lib functools.
-
It stores the previously computed data and use it for further.
-
Uses a bit more memory but saves in computational power of the hardware.
-
Here is a bad implementation of fibonacci function that gives the nth fibonacci number using recursion.
def fib(n): if n <= 1: return n return fib(n-1) + fib(n-2)
-
We create a main function that loops through a range of number, let's say, 400(0-399) and prints the index and the fibonacci number at that index.
def main(): for i in range(400): print(f'|> {i} >> {fib(i)}') print("done")
-
The implementation of this function use high computational power and recomputes every number again and again that makes it very inefficient, it takes forever to complete, the time increases as the index does.
-
Now, we use the cache decorator on top of the fibonacci function that stores the computed data and then reuse it if required.
from functools import cache @cache def fib(n): if n <= 1: return n return fib(n-1) + fib(n-2)
-
Now, the function auto-cache computed data and it finishes implementation in no time.
-
To save memory we can use the lru_cache decorator that takes up a max length to save the previously computed data rather than storing them all like in the cache operator.
from functools import cache, lru_cache @lru_cache(maxsize=5) def fib(n): if n <= 1: return n return fib(n-1) + fib(n-2)