Combining a map and a list for a cache
A least-recently-used cache remembers a limited number of items. A lookup table finds a key and an ordered list records which key was used most recently.
Simple example
A two-place cache receives keys 1, 2, 1 and 3. Looking up 1 refreshes it. Print the evicted key, 2.
let requests = [1, 2, 1, 3]
var recent = [-1, -1]
var i = 0
while i < 4 {
let key = requests[i]
if key != recent[0] {
if (key != recent[1] && recent[1] != -1) {
print(recent[1])
}
recent[1] = recent[0]
recent[0] = key
}
i += 1
}
2
Everyday examples
Keep two books on a desk
You read A, then B, then A again. Which book leaves when C arrives?
Reading A again makes it the more recent book. Remove B to make room.
Reuse a map tile
A phone already holds tile 7 and asks for 7 twice. How many cache entries should it use?
Refresh the existing entry. Adding a duplicate would waste one of the limited places.
Open a file after eviction
A one-place cache holds A. You open B, then reopen A. Where does the second A come from?
Opening B removed A. Fetch A again from storage and replace B.
Cost and limits
A hash map of nodes and a doubly linked list allow average O(1) lookups, moves and evictions. A small array can demonstrate the rule with a slower scan.