Readonly class properties in Typescript - Time & Space 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?
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.
- Primary operation: Looping through the array of points to calculate distance.
- How many times: Exactly n times, once for each point.
As the number of points n grows, the number of distance calculations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 distance calculations |
| 100 | 100 distance calculations |
| 1000 | 1000 distance calculations |
Pattern observation: The work grows directly with n, doubling n doubles the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of points.
[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.
Understanding how readonly properties affect performance helps you explain code design choices clearly and confidently.
"What if we added a nested loop inside the distance method to do extra work? How would the time complexity change?"