28/34
Part 7 of 7 · Follow-upsLearn and do

A length index makes best fit O(log k), and first fit needs a tree

On a plain list, best fit has to look at every run. A second index fixes that.

OrderThe three free runs
by start(0, 50), (60, 64), (70, 72)
by length, as (length, start)(2, 70), (4, 60), (50, 0)

Best fit for 3: bisect_left(by_length, (3, 0)) is 1, so it takes (4, 60), the run of 4 that starts at 60.

free is a binary search plus a shift, 8.6 µs at 100,000 runs above. First fit is a walk, 2,936 µs. To speed up the walk, index the runs a second way.

Keep the free runs sorted by length as well, as (length, start) pairs, and best fit is one bisect_left for (n, 0). That's O(log k) to search, with two lists to keep in step on every call.

Lea's allocator groups free chunks into bins by size, and his article describes the small ones: "Bins for sizes less than 512 bytes each hold only exactly one size (spaced 8 bytes apart, simplifying enforcement of 8-byte alignment)."

First fit by address can be made O(log k) too. Use a balanced search tree keyed by start, in which each node also records the longest run below it, so the search knows which side has room. Python's standard library has no such tree. Name it, give its cost, and don't write it in 45 minutes.

best_by_length(by_length, n) searches the free runs kept as (length, start) pairs, as in the second row of the table above. Write it with one bisect_left.