Declaring global variables in Typescript - Time & Space Complexity
When we declare global variables, we want to know how it affects the program's speed as it runs.
We ask: Does adding global variables make the program slower as it grows?
Analyze the time complexity of the following code snippet.
let count = 0;
function increment() {
count += 1;
}
increment();
increment();
This code declares a global variable count and a function that increases it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Simple variable assignment and addition.
- How many times: Each call to
increment()runs once, no loops or recursion.
Execution time stays about the same no matter how many global variables are declared.
| Input Size (number of global variables) | Approx. Operations |
|---|---|
| 10 | 10 simple assignments |
| 100 | 100 simple assignments |
| 1000 | 1000 simple assignments |
Pattern observation: Adding more global variables increases operations linearly, but each operation is very simple and does not repeat inside loops.
Time Complexity: O(n)
This means declaring or using global variables takes time proportional to the number of variables accessed or modified.
[X] Wrong: "Declaring many global variables makes the program slower because it has to manage all of them every time."
[OK] Correct: Each global variable is stored once and accessed directly; no repeated work happens just because they exist.
Understanding that global variables themselves do not add time cost helps you focus on what really affects performance, like loops or heavy calculations.
"What if we added a loop that updates a global variable many times? How would the time complexity change?"