Best Fit Memory Allocation in OS
Look at every free hole, keep the smallest one that is still big enough, and allocate from it. That wastes the least on each request and saves the big holes for big requests, at the price of a full scan and tiny leftovers.
How Best Fit Works
- Set 'best' to none
- For each hole that is big enough, keep it if it is smaller than the current best
- After the last hole, allocate from the best and keep the remainder free
- If no hole was big enough, the request waits
In operating system memory management, best fit gives a process the smallest free hole that can hold it. The allocator walks the whole free list, remembers the tightest candidate so far, and allocates from that one once the list is done. The hole is split and the remainder, as small as it can be, stays free.
It has no early exit: a later hole might always be tighter, so every hole has to be checked. The one exception is a hole of exactly the requested size, which cannot be beaten, so an implementation may stop there.
- Goal: the smallest leftover for this request
- Cost: a full pass over the list every time
Worked Example: Four Requests
Free holes of 100, 500, 200, 300 and 600 KB receive 212, 417, 112 and 426 KB. For 212 KB the candidates are 500 (288 spare), 300 (88 spare) and 600 (388 spare); the tightest is hole 4, leaving 88.
For 417 KB the candidates are 500 (83 spare) and 600 (183 spare): hole 2, leaving 83. For 112 KB they are 200 (88 spare) and 600 (488 spare): hole 3, leaving 88. For 426 KB only the 600 KB hole qualifies, and it is still whole: allocate, leaving 174. Every request was placed, after examining 5 holes each time.
- Holes used: 4, 2, 3, 5; nothing waits
- Free list after: 100, 83, 88, 88, 174 KB
- Holes examined in total: 20
Where It Wins and Where It Loses
The win is the 426 KB request. Because each earlier request found a tighter hole, the best fit algorithm never touched the 600 KB hole until it was the only one that would do. First fit, next fit and worst fit had all cut into it by then, and each ended with 959 KB free and the 426 KB request waiting.
The loss is the shape of what remains. Three of the five holes are now 83, 88 and 88 KB. If a 180 KB request came next, best fit memory allocation would fail with 533 KB free, because its largest hole is 174 KB, while the other three rules each still had a 300 KB hole. It also paid for a full scan every time: 20 holes examined against 14 for first fit and 12 for next fit.
- Kept the largest hole whole until a large request needed it
- Left three holes under 100 KB
- Examined every hole on every request
Best fit, request by request
def best_fit(holes, size):
best = -1
for i, hole in enumerate(holes):
if hole >= size and (best < 0 or hole < holes[best]):
best = i # tighter than any fit seen so far
return best, len(holes) # no early exit: every hole is examined
holes = [100, 500, 200, 300, 600]
total = 0
for size in [212, 417, 112, 426]:
i, looked = best_fit(holes, size)
total += looked
if i < 0:
print(f"{size} KB -> waits, largest hole is {max(holes)} KB, examined {looked}")
else:
holes[i] -= size # the rest of the hole stays free
print(f"{size} KB -> hole {i + 1}, leaves {holes[i]} KB, examined {looked}")
print("free list:", *holes)
print("holes examined:", total)#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
// Returns {hole index or -1, holes examined}.
std::pair<int, int> bestFit(const std::vector<int>& holes, int size) {
int best = -1;
for (int i = 0; i < (int)holes.size(); ++i)
if (holes[i] >= size && (best < 0 || holes[i] < holes[best]))
best = i; // tighter than any fit seen so far
return {best, (int)holes.size()}; // no early exit: every hole is examined
}
int main() {
std::vector<int> holes{100, 500, 200, 300, 600};
int total = 0;
for (int size : {212, 417, 112, 426}) {
auto [i, looked] = bestFit(holes, size);
total += looked;
if (i < 0) {
std::cout << size << " KB -> waits, largest hole is "
<< *std::max_element(holes.begin(), holes.end())
<< " KB, examined " << looked << "\n";
} else {
holes[i] -= size; // the rest of the hole stays free
std::cout << size << " KB -> hole " << i + 1 << ", leaves " << holes[i]
<< " KB, examined " << looked << "\n";
}
}
std::cout << "free list:";
for (int h : holes) std::cout << " " << h;
std::cout << "\nholes examined: " << total << "\n";
}public class Main {
// Returns {hole index or -1, holes examined}.
static int[] bestFit(int[] holes, int size) {
int best = -1;
for (int i = 0; i < holes.length; i++)
if (holes[i] >= size && (best < 0 || holes[i] < holes[best]))
best = i; // tighter than any fit seen so far
return new int[] {best, holes.length}; // no early exit: every hole is examined
}
public static void main(String[] args) {
int[] holes = {100, 500, 200, 300, 600};
int total = 0;
for (int size : new int[] {212, 417, 112, 426}) {
int[] r = bestFit(holes, size);
int i = r[0], looked = r[1];
total += looked;
if (i < 0) {
int largest = 0;
for (int h : holes) largest = Math.max(largest, h);
System.out.println(size + " KB -> waits, largest hole is " + largest + " KB, examined " + looked);
} else {
holes[i] -= size; // the rest of the hole stays free
System.out.println(size + " KB -> hole " + (i + 1) + ", leaves " + holes[i] + " KB, examined " + looked);
}
}
StringBuilder sb = new StringBuilder("free list:");
for (int h : holes) sb.append(" ").append(h);
System.out.println(sb);
System.out.println("holes examined: " + total);
}
}Step through it
Running on holes 100, 500, 200, 300, 600 KB · requests 212, 417, 112, 426 KB
What Measurement Shows
The name suggests it is the best choice, and the evidence is mixed rather than damning. Silberschatz reports that best fit and first fit both beat worst fit on speed and storage, with neither clearly ahead on storage and first fit usually faster. Studies of real program traces found best fit among the least wasteful policies, because real programs tend to free blocks of similar sizes together.
The search cost is fixable. Keeping holes in a balanced tree ordered by size finds the tightest fit in O(log n) instead of O(n), and allocators like dlmalloc work roughly this way within their size bins. The slivers are the part a data structure cannot fix; allocators handle them by rounding requests up or refusing to split off a remainder below a minimum size.
- Unsorted list: O(n) per request; size-ordered tree: O(log n)
- Minimum split size stops unusable slivers from entering the list