DEV Community

Dhravya
Dhravya

Posted on • Edited on

8 3

Write 1000x FAST Python using Automatic Memoization (one line of code)⚡

I came across this decorator in Functools which enables automatic Memoization of a function (Basically, storing what a certain function call returns and not having to run it again)

I'm about to blow your minds. and make the code more than 1000 times faster with just ONE line of code!

So here's a snippet that takes about 52 seconds to run. It's very slow and bad code because it's having to run the same fib() function multiple times. So every function call takes twice the amount of time the last function call. oh what a mess
bad slow code

Here's the magic ✨

By using the functool library's cache decorator, you can memoise the code automatically for much faster results!
Literally just one line of code (and the import, obviously)

from functools import cache

@cache
def fib(n):
    ...
Enter fullscreen mode Exit fullscreen mode

Just adding this makes the code run in JUST 0.013621500000000009 seconds! What's the cache here?(ha, get it? Catch ? cache?)
Basically all that the decorator is doing, is "remembering" the function call in memory, so this takes more RAM. But there's a way to make this even better.

It's by using the recently-used-cache decorator (lru_cache)

from functools import lru_cache

@lru_cache(maxsize=5)
Enter fullscreen mode Exit fullscreen mode

This only stores the last 5 function calls, which is much better. So here's the complete code:

LRU cache

How mind blowing is that!!

If you liked this little python trick, make sure to 💖 this post. If you REALLY liked it, Follow me here - https://dev.to/dhravya and if you REALLY REALLY liked it, follow me on twitter! https://twitter.com/dhravyashah

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

Top comments (0)

Neon image

Set up a Neon project in seconds and connect from a Python application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Value this insightful article and join the thriving DEV Community. Developers of every skill level are encouraged to contribute and expand our collective knowledge.

A simple “thank you” can uplift someone’s spirits. Leave your appreciation in the comments!

On DEV, exchanging expertise lightens our path and reinforces our bonds. Enjoyed the read? A quick note of thanks to the author means a lot.

Okay