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
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.
| Seed | First fit: failed | Best fit: failed | First fit: mean runs | Best fit: mean runs |
|---|---|---|---|---|
| 1 | 4,463 of 23,325 (19.13%) | 1,670 of 21,354 (7.82%) | 521 | 190 |
| 2 | 3,999 of 23,058 (17.34%) | 1,886 of 21,529 (8.76%) | 506 | 201 |
| 3 | 4,444 of 23,354 (19.03%) | 2,037 of 21,656 (9.41%) | 530 | 209 |
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.