0
0
Typescriptprogramming~5 mins

Readonly class properties in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Readonly class properties
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code with readonly class properties changes as the input grows.

Specifically, does making properties readonly affect how long the program takes to run?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Point {
  readonly x: number;
  readonly y: number;

  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }

  distance() {
    return Math.sqrt(this.x * this.x + this.y * this.y);
  }
}

const points: Point[] = [];
for (let i = 0; i < n; i++) {
  points.push(new Point(i, i));
}

for (const p of points) {
  console.log(p.distance());
}
    

This code creates n points with readonly x and y values, then calculates and prints their distances from the origin.

Identify Repeating Operations
  • Primary operation: Looping through the array of points to calculate distance.
  • How many times: Exactly n times, once for each point.
How Execution Grows With Input

As the number of points n grows, the number of distance calculations grows the same way.

Input Size (n)Approx. Operations
1010 distance calculations
100100 distance calculations
10001000 distance calculations

Pattern observation: The work grows directly with n, doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of points.

Common Mistake

[X] Wrong: "Making properties readonly makes the code run faster because values can't change."

[OK] Correct: Readonly only prevents changes in code but does not speed up how many times operations run.

Interview Connect

Understanding how readonly properties affect performance helps you explain code design choices clearly and confidently.

Self-Check

"What if we added a nested loop inside the distance method to do extra work? How would the time complexity change?"