Home Artificial Intelligence Tips on how to Use Python Built-In Decoration to Improve Performance Significantly 1. A Use Case of the Cache Decoration

Tips on how to Use Python Built-In Decoration to Improve Performance Significantly 1. A Use Case of the Cache Decoration

0
Tips on how to Use Python Built-In Decoration to Improve Performance Significantly
1. A Use Case of the Cache Decoration

Tips on how to implement a caching mechanism in Python, and when not to make use of it?

When talking about improving Python execution performance, especially for data processing, there are too many third party libraries that can assist us. If we take into consideration their mechanisms, most of them depend on optimising the info structure or utilisation of the memory to attain performance improvement.

For instance, Dask leverages parallel computing and memory optimisation, Pandas relies on vectorisation of the dataset and Modlin optimises the utilisation of the multi-cores CPU and memory, too.

In this text, I won’t introduce any libraries. In truth, there’s a native Python decoration that may very well be used to enhance the performance significantly. We don’t need to put in anything since it’s built-in to Python. In fact, it won’t be used for all of the scenarios. So, within the last section, I’ll also discuss when we must always not use it.

Image created in Canva by the creator

Let’s start with a vanilla example that we’re all accustomed to, the Fibonacci sequence. Below is a standard implementation using recursion.

def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)

Like most other programming languages, Python also needs to construct a “stack” for a recursive function and calculate the worth on every stack.

Nonetheless, the “cache” decoration will improve the performance significantly. Also, it shouldn’t be difficult to achieve this. We just have to import it from the functools module, after which add the decoration to the function.

from functools import cache

@cache
def fibonacci_cached(n):
if n < 2:
return n
return fibonacci_cached(n-1) + fibonacci_cached(n-2)

Listed here are the running results and the performance comparison.

LEAVE A REPLY

Please enter your comment!
Please enter your name here