LRU Cache — Data Structures

An LRU cache (Least Recently Used) is a cache, a place that keeps data you use often, with a fixed size. When it's full, it throws out the key unused the…

Your desk only has room for four books. To put down a fifth, one of them has to go back on the shelf. The sensible one to put back is the book you haven't touched for the longest.

That way of choosing a book is the rule of an LRU cache. A cache is a place that keeps data you use often, so you don't have to fetch or calculate it again. In the picture, the desk is the cache, and the books are the data in it. The problem: a cache has limited space. An LRU cache (Least Recently Used) has a simple rule for when it's full: throw out the item that has gone unused the longest. Many fixed-size caches use this rule, such as browser caches, and also Redis (a program that stores data) when it is set to use LRU. Redis uses an approximate LRU (it compares only a few keys picked at random), and it also has other rules, such as LFU, which throws out the data used least often, or volatile-ttl, which throws out the data whose expiry time ends soonest.

How it works: get and put

An LRU cache stores key and value pairs, like a hash map, and has two operations:

The important part: get counts as using a key too. A key you just read becomes the most recently used one.

Guess before you read the comments in this code: a cache holds 2 items. You store key 1, then key 2, read key 1, then store key 3. Is 1 or 2 thrown out?

const cache = new LRUCache(2); // holds 2 items (the class is built in the next section)
cache.put(1, "A");
cache.put(2, "B");
cache.get(1);      // "A", now 1 is the most recently used
cache.put(3, "C"); // full: 2 is thrown out, because 2 has gone unused the longest
cache.get(2);      // -1, 2 is gone
Step Cache contents (least recent → most recent) Note
put(1, "A") 1 still room
put(2, "B") 1, 2 now full
get(1) → "A" 2, 1 1 was just used, it moves to most recent
put(3, "C") 1, 3 full, 2 is the least recent: thrown out
get(2) → -1 1, 3 2 is gone

So 2 is thrown out, because get(1) had just used 1. In the Lab, the cache holds 4, a missing key gives back undefined, and the order is the reverse of this table: the most recently used key is shown on the far left, under the label MRU (most recently used). In the exercise, a missing key still gives back -1.

Building it with Map

A JavaScript Map stores key and value pairs and remembers the order they went in: the first key is the one that went in longest ago. The trick: every time a key is used, delete it and set it again, so it moves to the back. The key at the front is then always the one unused the longest.

This is the whole LRUCache class. this.map is the Map that holds the data, and this.capacity is the most items it can hold:

class LRUCache {
  constructor(capacity) {
    this.capacity = capacity;
    this.map = new Map();
  }

  get(key) {
    if (!this.map.has(key)) return -1;
    const value = this.map.get(key);
    this.map.delete(key);     // delete...
    this.map.set(key, value); // ...then set again: it moves to most recent
    return value;
  }

  put(key, value) {
    if (this.map.has(key)) {
      this.map.delete(key);   // an existing key: delete first so it becomes most recent
    } else if (this.map.size === this.capacity) {
      const oldest = this.map.keys().next().value;
      this.map.delete(oldest); // full: throw out the key at the front
    }
    this.map.set(key, value);
  }
}

Why it's fast: a hash map plus an order

A cache has to be quick at two things: finding a key, and knowing which key has gone unused the longest.

That's why a classic LRU cache combines the two. Each value in the hash map is a node in the list, so the node is found directly, and the list keeps the order. As a result, get and put are both O(1). A JavaScript Map happens to remember order already, which is why the code above is so short.

⚠️ When the wrong key gets thrown out

TL;DR: An LRU cache (Least Recently Used) is a cache, a place that keeps data you use often, with a fixed size. When it's full, it throws out the key unused the longest. Both get (read) and put (store) count as using a key, so the key moves to the most recent spot. With a Map: delete then set to move a key, map.keys().next().value for the oldest key, and -1 for a key that isn't there. A hash map finds a key in O(1), and a doubly linked list changes the order in O(1). A JavaScript Map does both.

⚡ Throw out the one unused the longest

Guess first: an LRU cache throws out the key unused the longest. Take an LRU cache that holds 2 keys. Store 1, store 2, read 1, then store 3. Is 1 or 2 thrown out?

2 is thrown out. Reading 1 (get(1)) counts as using it too, so 1 moves to the most recent spot, and 2 becomes the one unused the longest.

Meaning: An LRU cache is a cache (a place that keeps data you use often) with a fixed size. When it's full, it throws out the key unused the longest. Both put (store) and get (read) count as using a key, and get on a missing key gives back -1.

⚡ Delete, then set

Write:

const value = this.map.get(key);
this.map.delete(key);     // delete...
this.map.set(key, value); // ...then set again: it moves to most recent

Meaning: This is part of get in the LRUCache class. this.map is the Map where the cache keeps its data, and a Map remembers the order keys went in. Delete then set moves a key to the back, the most recently used spot. So the key at the front, this.map.keys().next().value, is always the one unused the longest.

⚡ A hash map plus an order

Meaning: A hash map finds a key in O(1), but an ordinary one doesn't keep the order of use. A doubly linked list keeps the order and moves a node in O(1). Together, get and put are both O(1). A JavaScript Map has both.

What you will learn