Lesson contents

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.

Start1 2 1 3
Result2
main.go
package main

import "fmt"

func main() {
    requests := []int{1, 2, 1, 3}
    recent := []int{-1, -1}
    i := 0
    for i < 4 {
        key := requests[i]
        if key != recent[0] {
            if (key != recent[1]) && (recent[1] != -1) {
                fmt.Println(recent[1])
            }
            recent[1] = recent[0]
            recent[0] = key
        }
        i += 1
    }
}
Output
2
Advertisements

Everyday examples

Keep two books on a desk

You read A, then B, then A again. Which book leaves when C arrives?

StartA B A +C
ResultB

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?

Start7 7
Result1

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?

StartA B A
ResultA

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.