7.3 Dynamic Storage Allocation Algorithms: First-Fit, Best-Fit & Worst-Fit
💡 Core Intuition
🍳 The Everyday Analogy: The Warehouse Storage Bays
Imagine managing a freight warehouse where incoming pallets of cargo must be placed into varying empty storage bays:
Warehouse Pallet Allocation Strategies
Contrasting speed, precision fit, and residual space conservation
First Available Bay
A forklift driver walks down aisle 1 and drops the cargo in the very first bay that fits.
Smallest Capable Bay
The manager searches every single aisle in the entire warehouse to find the tightest match.
Largest Cavernous Bay
Place the cargo inside the largest warehouse hangar currently empty.
- First-Fit: Prioritizes speed above all else. Scans from the start and grabs the first viable hole.
- Best-Fit: Prioritizes minimizing wasted partition space. Finds the smallest viable hole, but produces unusable micro-slivers.
- Worst-Fit: Prioritizes the utility of the leftover block. Chops into the largest hole so the remainder stays large and reusable.
💻 Bridging to Computer Science
In dynamic variable-size memory allocation, the operating system maintains a list of available free blocks of RAM known as the Free Hole List.
When a process of size enters the system:
- The memory manager searches the hole list for an available contiguous block such that .
- The allocator carves out bytes for the process.
- The remaining unallocated chunk (if greater than zero) is returned to the free list as a smaller hole.
The strategy chosen to select drastically influences both allocation latency (CPU time) and system fragmentation (RAM utilization).
| Allocation Algorithm | Search Traversal Rule | Candidate Hole Evaluated | Leftover Remainder Hole | Latency vs Fragmentation Trade-Off |
|---|---|---|---|---|
| First-Fit | First hole | Hole 2 () | Fastest search ( avg); leaves moderate leftover hole. | |
| Best-Fit | Smallest hole | Hole 4 () | Exhaustive search (); creates tiny unusable slivers. | |
| Worst-Fit | Largest hole in memory | Hole 5 () | Exhaustive search (); leaves large reusable remnant hole. |
📚 Core Deep-Dive & Concepts
1. The Four Allocation Algorithms
2. Time & Space Complexity Analysis
| Algorithm | Search Complexity (Unsorted List) | Search Complexity (Optimized Data Structure) | Fragmentation Pattern | Memory Utilization Efficiency |
|---|---|---|---|---|
| First-Fit | worst-case, early exit average | linked list | Small holes cluster near base | High (Consistently superior in practice) |
| Next-Fit | worst-case | circular linked list | Holes dispersed across entire RAM | Moderate |
| Best-Fit | (must inspect all entries) | via Balanced BST (e.g., Red-Black Tree) | Leaves tiny unusable slivers | Moderate to Low (creates useless dead space) |
| Worst-Fit | (must inspect all entries) | via Max-Heap (search max) | Destroys large contiguous blocks | Lowest (Fails large allocations quickly) |
Empirical Result (Knuth & Shore Experiments):
Exhaustive computer simulations show that First-Fit generally outperforms Best-Fit and Worst-Fit in both execution speed and storage utilization. First-Fit produces less severe fragmentation than Best-Fit, while Worst-Fit severely degrades system ability to satisfy large process requests.
3. Step-by-Step Allocation Trace: Comparative Walkthrough
Consider a physical memory configuration with free partitions/holes available in the following sequential order:
Four processes arrive sequentially with the following memory requests:
Let us trace the exact allocation sequence for all three primary algorithms:
A. First-Fit Allocation Trace
- () arrives:
- Check Hole 1 (): Too small.
- Check Hole 2 (): Fits! Allocated to .
- Remaining Hole 2 .
- State: .
- () arrives:
- Check Hole 1 (): Too small.
- Check Hole 2 (): Too small.
- Check Hole 3 (): Too small.
- Check Hole 4 (): Too small.
- Check Hole 5 (): Fits! Allocated to .
- Remaining Hole 5 .
- State: .
- () arrives:
- Check Hole 1 (): Too small.
- Check Hole 2 (): Fits! Allocated to .
- Remaining Hole 2 .
- State: .
- () arrives:
- Check Hole 1 (), Hole 2 (), Hole 3 (), Hole 4 (), Hole 5 ().
- None of the holes are !
- Result: cannot be allocated (must wait).
B. Best-Fit Allocation Trace
Initial State: .
- () arrives:
- Capable holes: .
- Smallest capable: Hole 4 (). Allocated to .
- Remaining Hole 4 .
- State: .
- () arrives:
- Capable holes: .
- Smallest capable: Hole 2 (). Allocated to .
- Remaining Hole 2 .
- State: .
- () arrives:
- Capable holes: .
- Smallest capable: Hole 3 (). Allocated to .
- Remaining Hole 3 .
- State: .
- () arrives:
- Capable holes: Hole 5 ().
- Smallest capable: Hole 5 (). Allocated to !
- Remaining Hole 5 .
- Result: All four processes () successfully allocated!
C. Worst-Fit Allocation Trace
Initial State: .
- () arrives:
- Largest hole: Hole 5 (). Allocated to .
- Remaining Hole 5 .
- State: .
- () arrives:
- Largest hole: Hole 2 (). Allocated to .
- Remaining Hole 2 .
- State: .
- () arrives:
- Largest hole: Hole 5 (). Allocated to .
- Remaining Hole 5 .
- State: .
- () arrives:
- Available holes: .
- Largest available hole is only .
- Result: cannot be allocated (must wait).
Summary Comparison for this Workload
| Algorithm | () | () | () | () | Total Completed |
|---|---|---|---|---|---|
| First-Fit | Hole 2 () | Hole 5 () | Hole 2 () | ❌ Rejected | 3 / 4 |
| Best-Fit | Hole 4 () | Hole 2 () | Hole 3 () | ✅ Hole 5 () | 4 / 4 (Winner) |
| Worst-Fit | Hole 5 () | Hole 2 () | Hole 5 () | ❌ Rejected | 3 / 4 |
🏭 In The Real World: Production Case Study
High-Performance Heap Memory Allocators: malloc & ptmalloc
Modern user-space allocators implement modified hybrid forms of these algorithms to maximize thread concurrency and minimize heap fragmentation:
GNU C Library (glibc) ptmalloc Arena Architecture
Multi-tier bin hierarchy balancing allocation speed and fragmentation control
Fastbins
Singly-Linked (16B - 80B)- Dedicated singly-linked LIFO caches for tiny allocation sizes.
- Zero hole scanning: allocations and deallocations complete in O(1) time via lockless pointer swaps.
Smallbins
Exact-Fit (< 512B)- Doubly-linked circular FIFO queues partitioned into 64 distinct exact size classes.
- Guarantees deterministic O(1) allocation without splitting large contiguous memory chunks.
Unsorted Bin
First-Fit Staging- Immediate cache staging area for all recently freed non-fastbin memory chunks.
- Evaluated via First-Fit: quickly recycles recently freed blocks without tree searches.
Largebins
Best-Fit (> 512B)- Sorted balanced search trees housing varied variable-sized large memory chunks.
- Searched via Best-Fit to strictly minimize wasted external fragmentation on large requests.
- Why
mallocDoes Not Use Pure Worst-Fit:- In production microservices allocating millions of JSON strings, Worst-Fit quickly breaks apart large contiguous memory maps (
mmapregions), causing heap expansion and out-of-memory (OOM) errors.
- In production microservices allocating millions of JSON strings, Worst-Fit quickly breaks apart large contiguous memory maps (
- The Fastbin Optimization:
glibcbypasses dynamic hole searching entirely for small sizes by using dedicated Fastbins (analogous to fixed-size partitioning). Deallocations and allocations execute in time through pointer swaps without scanning any hole lists.
🎯 Exam & Interview Pitfall Check
Question 1: In dynamic memory allocation, why is Worst-Fit named "Worst-Fit" if its design goal was to leave behind large, reusable fragments? Answer:
- The name refers to the heuristic: it intentionally selects the worst possible size match (the largest discrepancy between request size and available hole size).
- While the intention was to keep residual fragments large enough to be useful, in practice it rapidly consumes and splinters the largest contiguous blocks in the system.
- When a subsequent process arrives with a genuinely large memory requirement, the system cannot fulfill the request because the large holes have already been degraded. Consequently, Worst-Fit exhibits the worst performance in overall storage utilization.
Question 2: Which algorithm is preferred when memory allocation requests arrive at an exceptionally high frequency and low CPU overhead is paramount? Answer: First-Fit is preferred.
- First-Fit does not require examining all free blocks; it terminates searching as soon as the first satisfactory hole is encountered.
- In contrast, Best-Fit and Worst-Fit must inspect every single block in an unsorted free list to determine the global minimum or maximum, incurring significant CPU scanning latency.
- The "Best-Fit is Always Best" Trap: Do not assume Best-Fit is globally optimal because of its name. In variable-size partitioning, Best-Fit creates swarms of tiny unallocated fragments (e.g. 4-byte or 8-byte holes) that cannot satisfy any realistic process request, degrading performance over time.
- Failure to Update Hole Sizes in Multi-Step Questions: When tracing problems on exams, remember that after satisfying a process request, the hole size decreases immediately. The next process in the sequence sees the updated hole size, not the original size.