LRU Cache in Python29 Aug 2024 | 7 min read In this tutorial, we will learn about the LRU cache in Python. We will learn the caching strategies and how to implement them using the Python decorators, the LRU strategy, and how it works. We will also discuss how to improve performance by caching with the @lru_cache decorator. This tutorial consists of a deeper understanding of how caching works and how to get benefit from it in Python. First, let's understand what caching is and its uses. Caching and Its UsesCaching is the best technique of memory management, which restores the most recent or often data in the memory so that we can access faster or computationally cheaper than their actual source. The LRU cache follows the First in First Out format. Let's take a real life example to understand it in better way. Suppose we are creating a website that fetches the articles from the different sites. As user clicks on the particular list, the application downloads the articles and shows to the screen. What happen when users decide to move back the visited articles? If our application is not facilitates with the caching technique then it will download the same content again and again. That would make the application's system very slow and put extra pressure on the server hosting the articles. The application would store the content locally after fetching each article to overcome such a situation. The next time user decided to open the article, the application would fetch content from the locally stored copy instead of going back to the resource. This technique is known as caching. What is LRU Caching?The LRU Caching is known as the Least Recently Used, which is a common caching strategy to define the policy to evict elements and make place for new elements. It discards the least recently used items first when the cache is full. In the LRU, there are two references used -
Implementing a Cache Using a Python DictionaryWe can implement a caching solution using a Python dictionary. Let's take the articles reference; instead of visiting the direct to the server, we can check it in the cache and return it to the server. Let's understand the following example. Example - Output: Getting article... Fetching article from server... Getting article... Fetching article from server... Explanation - In the above code, we can see that we get the string "Fetching article from server" because after accessing the article for the first time, we put its URL and content in the cache dictionary. When we run the code second time, we don't need to fetch the item from the server again. Various Caching StrategiesWe need to have the proper strategy to decide to make the application more efficient. In our application, when the user downloads more articles, it keeps storing them in the memory, which can lead to an application crash. A suitable strategy can resolve such an issue using algorithms that focus on managing the cache information and which item to remove to make room for the new item. There are various strategies that can be used to expel the cache and make the space for the new one. Let's see the popular caching strategies below.
We will use Python's @lru_cache decorator functools module in the upcoming section. LRU (Least Recent Used) Caching StrategyThe LRU strategy is popularly known for organizing its items to use. The LRU algorithm moves the entry at the top of the cache when we try to access it. And this is how the algorithm identifies the entry that's gone unused by checking the bottom of the list. When the new entry comes, it pushes the first entry down the list. This algorithm assumes that the more likely it will be needed in the future if an object has been used. Create LRU Cache in PythonIn this section, we will create the simple LRU cache implementation using Python's features. Python comes with the hash table known as the OrderedDict that keeps the order of the insertion of the keys. We use the following strategy to achieve it.
Example - Output: OrderedDict([('1', '1'), ('3', '3'), ('4', '4')]) OrderedDict([('3', '3'), ('4', '4'), ('5', '5')]) Explanation Let's breakdown the code -
Create LRU Cache in Python Using functoolsHere we will use the @lru_cache decorator of the functools module. However, @lru_cache uses it behind the scene. We can apply this decorator to any function which takes a potential key as an input and returns the corresponding data object. The advantage is that when the function is called again, the decorator will not execute the function statements if the data corresponding is already present in the cache. Let's understand the following example. Example - Output: Cache miss with 1 1: value Cache miss with 2 2: value Cache miss with 3 3: value Cache miss with 4 4: value 4: value 3: value 1: value Cache miss with 7 7: value Cache miss with 6 6: value 3: value 1: value Evicting Cache Entries Based on Both Time and SpaceThe @lru_cache decorator expels existing entries only when there are no space stores more entries. If the entries are sufficient, they will live last long and never get a refresh. So we can implement such functionality to update the cache system, so it expires after a specific time. We can implement it using the @lru_cache, as we discussed earlier. If the caller tries to access an item past its lifetime, the cache won't return its content and force the caller to fetch the result directly from the network. Let's understand the following example - Example - Let's breakdown the code -
We can implement this strategy more sophisticatedly by evicting the entries based on their individual lifetimes. ConclusionCaching is an important strategy for improving the performance of any software system. We have explained some important concepts related to the LRU and how we can implement it using various techniques such as - @lru_cache and OrderDict. It also includes the measure the runtime of the code using the timeit module. |
One of the fundamental concepts in statistics is the study of random variables and their distributions. This tutorial gives you a thorough understanding of Poisson Discrete Distribution, which is a key component in statistics/probability theory, and finally, learn about its various properties and calculations using Python. Let...
11 min read
In the ious tutorial, we have understood the concept of Distributed Computing and Introduction to Dask. We have also understood what Dask Cluster is and how to install Dask in addition to the introduction to the Dask Interface. Dask Interface As we have already discussed, Dask Interfaces have...
27 min read
The edit distance between two strings measures the minimum number of operations that are needed to convert one string into another. There are various operations that may be performed, including insertion, deletion, and substitution of a single character. The edit distance is also referred to...
8 min read
The most adaptable language is Python, which is used in nearly every industry, including game development, web development, machine learning, artificial intelligence, and GUI applications. The game is developed using the pygame package, which is a built-in feature of Python. With a rudimentary understanding of Python programming,...
12 min read
In Python, a string is a sequence of characters, and a list is a collection of elements that can be of any data type, including strings. Subtraction of a string list involves removing elements that are common between two lists or strings. To subtract one string list...
4 min read
Introduction In this article, we are discussing procurement analysis projects with python. As a store manager of a mid-size retail vicinity, you set the replenishment amount within the ERP. While the stock degree is beneath a positive threshold for each SKU, your ERP sends an automatic buy...
6 min read
Python is a definition for the Scripting language, which may be used in various ways. The scripting language Python employs many interpreters, each of which is different. Plenty of Python interpreters are available since it will be the programming language with the highest growth in 2023....
12 min read
In this tutorial, we will learn about the FlashText module and how to replace words in the text sequences using FlashText. This provides the efficient ways of replacing a large set of words in a textual document. Working of FlashText Algorithm The FlashText algorithm is built upon the...
3 min read
Dictionary is one of the most used data types in Python. It is an unordered collection of key: value pairs. Every value has a corresponding key that identifies it. A dictionary is a mutable collection, meaning we can modify the values. One factor that makes a...
4 min read
One of the most important and widely used data structures within Python programming is the dictionary. When using Python to programme, it is not unusual to want to mix two or more dictionaries. In this article, we shall examine various approaches, examples, and results for merging...
4 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India