Garbage collection overview in Java - Time & Space Complexity
We want to understand how the time cost of garbage collection changes as the program creates more objects.
How does the cleanup work when there are many objects to manage?
Analyze the time complexity of this simplified garbage collection process.
// Simplified garbage collection scan
import java.util.Iterator;
Iterator
This code scans all objects in the heap and removes those that are not reachable.
Look for repeated actions that take time.
- Primary operation: Looping through all objects in the heap.
- How many times: Once for each object in the heap.
As the number of objects grows, the time to check each one grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The time grows directly with the number of objects.
Time Complexity: O(n)
This means the garbage collector's work grows in a straight line with the number of objects it checks.
[X] Wrong: "Garbage collection time stays the same no matter how many objects exist."
[OK] Correct: The collector must look at each object to decide if it's still needed, so more objects mean more work.
Understanding how garbage collection time grows helps you explain performance in programs that create many objects.
"What if the garbage collector used multiple threads to scan objects in parallel? How would the time complexity change?"
