Sitemap
Pystar

Pystar

Python, Django, JavaScript, DevOps. Member of @thepsf

Run Python, Run!!!

1 min readFeb 15, 2019

Do you want a speed increase of up to 20% in your code?

Speed up your python programs with a powerful, yet convenient caching decorator?

Do you know you can achieve this easily with just a single line of code?

***drumroll***

Introducing lru_cache().

Get Pystar’s stories in your inbox

Join Medium for free to get updates from this writer.

lru_cache is a function decorator imported from the standard library functools module. It’s Pythons easy to use take on memoization.

How it works: It wraps itself around constantly called functions, caching the result of the function invocation thereby providing a speed boost.

Simplistically, the lru_cache consists of a cache dictionary and a linked list.

The cache dictionary keeps track of the function return values and the linked list keeps track of the function call history.

Using the timeit module, I noticed up to 20% increase in speed for certain benchmarks. This is due to the good work of developers who rewrote the functools.lru_cache() decorator in C for Python 3.5.

The lru_cache decorator is so simple and easy to use like all things Python.
I advise you use it.

--

--

Pystar
Pystar

Written by Pystar

Python, Django, JavaScript, DevOps. Member of @thepsf