Object creation in Java - Time & Space Complexity
When we create objects in Java, it takes some time for the computer to set up each new object.
We want to understand how the time needed grows as we create more objects.
Analyze the time complexity of the following code snippet.
public class Example {
public static void createObjects(int n) {
for (int i = 0; i < n; i++) {
Object obj = new Object();
}
}
}
This code creates n new objects one after another in a loop.
- Primary operation: Creating a new object inside the loop.
- How many times: The loop runs
ntimes, sonobjects are created.
Each time we increase n, we create more objects, so the time grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations |
| 100 | 100 object creations |
| 1000 | 1000 object creations |
Pattern observation: If you double the number of objects to create, the time roughly doubles too.
Time Complexity: O(n)
This means the time to create objects grows in a straight line with the number of objects you want to make.
[X] Wrong: "Creating objects inside a loop is instant and does not affect performance."
[OK] Correct: Each object creation takes time, so doing it many times adds up and affects how long the program runs.
Understanding how object creation time grows helps you write code that runs smoothly and shows you can think about efficiency clearly.
"What if we created objects only when a condition inside the loop is true? How would the time complexity change?"