15/30
Part 4 of 7 · Why not a heapLearn and do

Stale keys pile up, and sorted lists stay small

Every update leaves one stale key behind. After a million updates on a catalog of 1,000 titles, the heap holds about a million keys, and nearly all of them are dead. The fix is to rebuild now and then: when stale keys outnumber live ones, throw the heap away and heapify a fresh one from the scores dict, in O(n).

Here's what one update cost, measured in Python 3.12 with random scores. Each number is microseconds per update, best of 3 runs:

Per update1,000 titles10,000100,000
heap: push a second key0.59 µs0.89 µs1.04 µs
two sorted lists: find, delete, insort1.24 µs3.16 µs20.10 µs
scan every title for the best (one get)71.53 µs625.73 µs6,538.52 µs
sort the whole catalog again189.04 µs2,822.85 µs56,572.44 µs
One update or get at 100,000 titles, log scale
heap push
1.04 µs
sorted lists
20.1 µs
scan
6,539 µs
sort again
56,572 µs

The heap's push is fastest, but it's only half the work. It moves the cost into get, which pops stale keys, and into the rebuilds. The sorted lists pay a little more per update and never hold a dead key, so get stays one pop. Both beat re-sorting by a factor of thousands.

So why do candidates steer away from the heap? Not speed. It's the bookkeeping: a scores dict to spot stale keys, a shown set, a rebuild rule, and a second heap or a rebuild at every loop. Two sorted lists need none of that. In Java, a TreeMap or TreeSet gives O(log n) for every step. Python has no sorted container built in, and bisect on a list is the plain substitute.

The editor holds compact and stale. Write compact(heap, scores) to rebuild a fresh heap with one key per title, and stale(heap, scores) to count the dead keys.