Static members with types in Typescript - Time & Space Complexity
We want to understand how the time it takes to access or use static members in a class changes as the program runs.
Specifically, does using static members with types affect how long operations take?
Analyze the time complexity of the following code snippet.
class Counter {
static count: number = 0;
static increment() {
this.count += 1;
}
}
for (let i = 0; i < n; i++) {
Counter.increment();
}
This code defines a class with a static number and a method to increase it. Then it calls that method n times in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the static method
increment()which updates a static variable. - How many times: The method is called once for each loop iteration, so
ntimes.
Each time we increase n, the loop runs that many times, calling the static method each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to increment() |
| 100 | 100 calls to increment() |
| 1000 | 1000 calls to increment() |
Pattern observation: The number of operations grows directly with n. Double n, double the calls.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of times we call the static method.
[X] Wrong: "Accessing static members is instant and does not add to time as n grows."
[OK] Correct: While accessing a static member is fast, calling a method that updates it inside a loop still happens n times, so total time grows with n.
Understanding how static members behave in loops helps you explain performance clearly and shows you know how code scales with input size.
"What if the static method did not update any variable but only returned a fixed value? How would the time complexity change?"