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 update | 1,000 titles | 10,000 | 100,000 |
|---|---|---|---|
| heap: push a second key | 0.59 µs | 0.89 µs | 1.04 µs |
| two sorted lists: find, delete, insort | 1.24 µs | 3.16 µs | 20.10 µs |
scan every title for the best (one get) | 71.53 µs | 625.73 µs | 6,538.52 µs |
| sort the whole catalog again | 189.04 µs | 2,822.85 µs | 56,572.44 µ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.