Class property declarations in Typescript - Time & Space Complexity
Let's see how the time it takes to run code changes when we use class property declarations in TypeScript.
We want to know how declaring properties affects the work done when creating objects.
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 n Person objects, each with two properties set during construction.
- Primary operation: Creating a new Person object and assigning its properties inside the constructor.
- How many times: This happens once for each of the n iterations in the loop.
Each new object requires setting two properties, and this happens for every item in the loop.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 property assignments (2 per object x 10 objects) |
| 100 | About 200 property assignments |
| 1000 | About 2000 property assignments |
Pattern observation: The work grows directly with the number of objects created.
Time Complexity: O(n)
This means the time to create all objects grows in a straight line as we add more objects.
[X] Wrong: "Declaring properties inside the class makes object creation instant or constant time regardless of how many objects."
[OK] Correct: Each object still needs its own properties set, so the time grows with the number of objects created.
Understanding how object creation scales helps you explain performance when working with many instances in real projects.
What if we added a loop inside the constructor that runs m times? How would the time complexity change?