Access modifiers public private protected in Typescript - Time & Space Complexity
Let's see how using access modifiers affects the speed of running TypeScript code.
We want to know if public, private, or protected changes how long the program takes as it grows.
Analyze the time complexity of the following code snippet.
class Counter {
private count = 0;
public increment() {
this.count++;
}
protected getCount() {
return this.count;
}
}
const counter = new Counter();
for (let i = 0; i < 1000; i++) {
counter.increment();
}
This code defines a class with public, private, and protected parts, then calls a method many times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop calling
increment()1000 times. - How many times: Exactly 1000 times, each increasing the count by one.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: The number of operations grows directly with the number of increments.
Time Complexity: O(n)
This means the time to run grows in a straight line as the number of increments grows.
[X] Wrong: "Using private or protected slows down the code because of extra checks."
[OK] Correct: Access modifiers are for organizing code and controlling access, but they do not add extra time when running loops or methods.
Understanding that access modifiers do not affect how fast your code runs helps you focus on writing clear and safe code without worrying about speed.
"What if the increment method called another method inside the class multiple times? How would the time complexity change?"