0
0
Typescriptprogramming~5 mins

Class property declarations in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Class property declarations
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations
  • 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.
How Execution Grows With Input

Each new object requires setting two properties, and this happens for every item in the loop.

Input Size (n)Approx. Operations
10About 20 property assignments (2 per object x 10 objects)
100About 200 property assignments
1000About 2000 property assignments

Pattern observation: The work grows directly with the number of objects created.

Final Time Complexity

Time Complexity: O(n)

This means the time to create all objects grows in a straight line as we add more objects.

Common Mistake

[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.

Interview Connect

Understanding how object creation scales helps you explain performance when working with many instances in real projects.

Self-Check

What if we added a loop inside the constructor that runs m times? How would the time complexity change?