Constructor parameter types in Typescript - Time & Space Complexity
Let's see how the time it takes to run code changes when we use constructor parameters in TypeScript classes.
We want to know how the number of operations grows as we create more objects with parameters.
Analyze the time complexity of the following code snippet.
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
const people: Person[] = [];
for (let i = 0; i < n; i++) {
people.push(new Person(`Name${i}`, i));
}
This code creates a list of Person objects, each with a name and age passed to the constructor.
- Primary operation: Creating a new Person object inside a loop.
- How many times: The loop runs n times, so the constructor runs n times.
Each time we add one more person, we do one more constructor call and one more push to the array.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 constructor calls and 10 pushes |
| 100 | About 100 constructor calls and 100 pushes |
| 1000 | About 1000 constructor calls and 1000 pushes |
Pattern observation: The number of operations grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to create all objects grows in a straight line as we add more items.
[X] Wrong: "The constructor runs only once, so the time is constant regardless of n."
[OK] Correct: The constructor runs every time we create a new object, so it runs n times when we create n objects.
Understanding how constructors affect performance helps you explain object creation costs clearly and confidently in real projects.
"What if the constructor did some extra work inside a loop for each object? How would the time complexity change?"