19/37
Part 4 of 6 · Time limitsLearn and do

Sweep with a heap, so a sweep touches only the heap entries that are due

Scanning every entry costs O(n), however few have expired

The fix for entries nobody reads is a sweep: a purge() that removes everything expired. It runs on a timer, or when the cache needs room. The obvious sweep walks every entry and checks it. That's O(n) per sweep, however few entries have expired.

Here are n entries written at time 0, 10 of them with ttl=5 and the rest with ttl=1000, swept once at time 10. A full scan against the heap version below, median of 5 runs, same laptop:

EntriesScan every entryPop from a heap
10,0000.83 ms0.015 ms
100,0007.99 ms0.034 ms
1,000,00077.2 ms0.134 ms

Each sweep removed the same 10 entries. The scan's time grew with every entry it had to look at.

In the editor, write that scan as scan_purge(entries, now): delete every expired entry and return how many went. entries maps each key to (value, expires_at), as in TTLCache.