Register allocation and assignment in Compiler Design - Time & Space Complexity
When a compiler assigns variables to a limited number of CPU registers, it needs to decide efficiently which variable goes where.
We want to understand how the time to assign registers grows as the number of variables increases.
Analyze the time complexity of the following register allocation approach.
for each variable v in variables:
for each register r in registers:
if r is free for v's live range:
assign v to r
break
if no register found:
spill v to memory
This code tries to assign each variable to a free register during its usage period, spilling to memory if none is free.
Look at the loops that repeat work:
- Primary operation: Checking each register for each variable to find a free one.
- How many times: For every variable, the inner loop runs up to the number of registers.
As the number of variables grows, the compiler checks more registers for each one.
| Input Size (n variables) | Approx. Operations |
|---|---|
| 10 | 10 x number_of_registers |
| 100 | 100 x number_of_registers |
| 1000 | 1000 x number_of_registers |
Pattern observation: The work grows linearly with the number of variables, multiplied by the fixed number of registers.
Time Complexity: O(n)
This means the time to assign registers grows roughly in direct proportion to the number of variables.
[X] Wrong: "Register assignment takes the same time no matter how many variables there are."
[OK] Correct: More variables mean more checks to find free registers, so time increases with variable count.
Understanding how register allocation scales helps you explain compiler efficiency clearly and shows you can reason about resource limits in real systems.
"What if the number of registers also grew with the number of variables? How would that affect the time complexity?"