Object lifecycle in Java - Time & Space Complexity
We want to understand how the time to create and destroy objects changes as we make more objects.
How does the program's work grow when handling many objects?
Analyze the time complexity of the following code snippet.
public class ObjectLifecycle {
public static void main(String[] args) {
int n = 1000;
for (int i = 0; i < n; i++) {
MyObject obj = new MyObject();
obj.doWork();
}
}
}
class MyObject {
void doWork() {
// some simple operation
}
}
This code creates n objects one after another and calls a simple method on each.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating an object and calling its method.
- How many times: Exactly n times, once per loop iteration.
Each new object adds a fixed amount of work, so the total work grows steadily as n grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations and method calls |
| 100 | 100 object creations and method calls |
| 1000 | 1000 object creations and method calls |
Pattern observation: The work increases directly in proportion to the number of objects.
Time Complexity: O(n)
This means the time grows in a straight line as you create more objects.
[X] Wrong: "Creating objects is free or constant time regardless of how many are made."
[OK] Correct: Each object creation takes time, so making more objects adds more work.
Understanding how object creation scales helps you write efficient code and explain your reasoning clearly in interviews.
"What if the doWork() method itself contained a loop that ran n times? How would the time complexity change?"