Object.create usage in Javascript - Time & Space Complexity
Let's explore how using Object.create affects the time it takes for a program to run.
We want to know how the work grows when we create many objects this way.
Analyze the time complexity of the following code snippet.
const proto = { greet() { return 'Hello'; } };
function createObjects(n) {
const arr = [];
for (let i = 0; i < n; i++) {
arr.push(Object.create(proto));
}
return arr;
}
This code creates an array of n objects, each linked to the same prototype.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop runsntimes, creating one object each time. - How many times: Exactly once per object, so
ntimes total.
As n grows, the number of objects created grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations |
| 100 | 100 object creations |
| 1000 | 1000 object creations |
Pattern observation: The work grows directly with the number of objects you want to create.
Time Complexity: O(n)
This means the time to create objects grows in a straight line with how many objects you make.
[X] Wrong: "Using Object.create is instant and does not depend on how many objects we create."
[OK] Correct: Each call to Object.create makes a new object, so more objects mean more work and more time.
Understanding how object creation scales helps you write efficient code and explain your choices clearly in interviews.
"What if we replaced the for loop with a recursive function creating objects? How would the time complexity change?"