0
0
Typescriptprogramming~5 mins

Getter and setter with types in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Getter and setter with types
O(n)
Understanding Time Complexity

Let's see how the time it takes to run code with getters and setters changes as we use more data.

We want to know how the number of operations grows when we access or change values using getters and setters.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Person {
  private _age: number;

  constructor(age: number) {
    this._age = age;
  }

  get age(): number {
    return this._age;
  }

  set age(value: number) {
    if (value >= 0) {
      this._age = value;
    }
  }
}

const people: Person[] = [];
for (let i = 0; i < 1000; i++) {
  people.push(new Person(i));
}

for (const person of people) {
  console.log(person.age);
  person.age = person.age + 1;
}
    

This code creates many Person objects, then reads and updates their age using getters and setters.

Identify Repeating Operations
  • Primary operation: Looping through the array of Person objects to get and set age.
  • How many times: Once for each person in the array (1000 times in this example).
How Execution Grows With Input

Each person's age is accessed and updated once, so the total work grows directly with the number of people.

Input Size (n)Approx. Operations
10About 20 (10 gets + 10 sets)
100About 200 (100 gets + 100 sets)
1000About 2000 (1000 gets + 1000 sets)

Pattern observation: The number of operations grows in a straight line as the input size increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to get and set ages grows directly with how many Person objects there are.

Common Mistake

[X] Wrong: "Getters and setters add hidden loops making the code slower than a simple property."

[OK] Correct: Getters and setters run just like normal property access, so they don't add extra loops or slow down the code beyond the main loop.

Interview Connect

Understanding how getters and setters affect performance helps you explain your code clearly and shows you know how data access scales in real projects.

Self-Check

"What if the setter included a loop inside it? How would the time complexity change when updating ages?"