Object creation in Javascript - Time & Space Complexity
Let's explore how the time it takes to create objects changes as we create more of them.
We want to know how the work grows when making many objects.
Analyze the time complexity of the following code snippet.
const createObjects = (n) => {
const result = [];
for (let i = 0; i < n; i++) {
const obj = { id: i, value: i * 2 };
result.push(obj);
}
return result;
};
This code creates an array of n objects, each with two properties.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating one object inside the loop.
- How many times: Exactly n times, once per loop iteration.
Each time we increase n, we create more objects one after another.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 objects created |
| 100 | 100 objects created |
| 1000 | 1000 objects created |
Pattern observation: The work grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time to create objects grows in a straight line with the number of objects.
[X] Wrong: "Creating many objects is instant and does not depend on how many we make."
[OK] Correct: Each object takes some time to make, so more objects mean more total time.
Understanding how object creation scales helps you write efficient code and explain your reasoning clearly in interviews.
"What if we added a nested loop inside to create objects inside objects? How would the time complexity change?"