Constructor functions in Javascript - Time & Space Complexity
Let's see how the time it takes to create objects with constructor functions changes as we make more objects.
We want to know how the work grows when making many objects using a constructor.
Analyze the time complexity of the following code snippet.
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log(`Hi, I am ${this.name}`);
};
}
const people = [];
for (let i = 0; i < n; i++) {
people.push(new Person(`Person${i}`, 20 + i));
}
This code creates n person objects using a constructor function and stores them in an array.
- Primary operation: Creating a new
Personobject inside the loop. - How many times: The loop runs
ntimes, so the constructor runsntimes.
Each time we add one more person, the work grows by one constructor call.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 constructor calls |
| 100 | 100 constructor calls |
| 1000 | 1000 constructor calls |
Pattern observation: The work grows directly with the number of objects created.
Time Complexity: O(n)
This means if you double the number of objects, the time to create them roughly doubles too.
[X] Wrong: "Creating many objects with a constructor is instant and does not depend on how many objects we make."
[OK] Correct: Each object needs time to be created, so more objects mean more time spent.
Understanding how object creation scales helps you write efficient code and explain your reasoning clearly in interviews.
"What if the constructor function included a loop inside it? How would that affect the time complexity when creating n objects?"