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.
requests <- c(1, 2, 1, 3)
recent <- c(-1, -1)
i <- 0
while (i < 4) {
key <- requests[(i) + 1]
if (key != recent[(0) + 1]) {
if ((key != recent[(1) + 1]) && (recent[(1) + 1] != -1)) {
cat(recent[(1) + 1], "\n", sep = "")
}
recent[(1) + 1] <- recent[(0) + 1]
recent[(0) + 1] <- key
}
i <- 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.