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

What interviewers ask next

Once the levels pass, the follow-ups compare designs, starting with how to pick a run.

First fit or best fit: on one random workload, best fit failed about half as often

Requests 2, then 5, on an arena of 8
01234567
start
first fit
AA
5 fails: runs of 3 and 2.
best fit
BBBBBAA
Both fit.
Requests 3, 3, then 4, on an arena of 11
012345678910
start
first fit
AAABBBCCCC
All three fit.
best fit
BBBAAA
4 fails: runs of 3 and 1.

Best fit takes the smallest run that fits instead of the lowest. It can leave big runs whole for big requests, as in the first case. It can also leave slivers too small to use, as in the second. Neither rule wins on every sequence of requests, so the question is which wins more often.

Here are the two on one random workload:

  • The arena has 100,000 units.
  • The workload runs 40,000 steps.
  • An allocation asks for int(2 ** rng.uniform(0, 10)) units: 1 to 1,023, with small sizes more likely.
  • A step allocates while fewer than 90% of the units are in use, and otherwise frees a random live block.
  • Every request that failed had at least 10,000 units free in total, ten times the largest request, so every failure was fragmentation.
SeedFirst fit: failedBest fit: failedFirst fit: mean runsBest fit: mean runs
14,463 of 23,325 (19.13%)1,670 of 21,354 (7.82%)521190
23,999 of 23,058 (17.34%)1,886 of 21,529 (8.76%)506201
34,444 of 23,354 (19.03%)2,037 of 21,656 (9.41%)530209

On this workload best fit failed about half as often and kept about 60% fewer runs. With the same workload held under 80% full, failures were rare for both: 15 to 20 per run for first fit and 4 to 7 for best fit, out of about 20,000 requests.

A random workload isn't a real program, so don't quote it as a law. The real-program evidence comes from a survey that Doug Lea cites in his article on dlmalloc, the allocator that glibc's manual says its own is derived from: "As shown by Wilson et al, best-fit schemes (of various kinds and approximations) tend to produce the least fragmentation on real loads compared to other general approaches such as first-fit."

The cost is the search. Best fit can't stop at the first run that fits, so on a plain list it walks all k runs every time.

first_fit and best_fit are in the editor, finished. Write failures(free, sizes, pick), which serves a list of requests with one of the two rules and counts the failures, and run it on the two figures above.