Namespace declaration in Typescript - Time & Space Complexity
When we use namespaces in TypeScript, we group code together. It's important to see how this grouping affects how long the program takes to run.
We want to know: does using namespaces change how the program's speed grows as we add more code inside them?
Analyze the time complexity of the following code snippet.
namespace MathUtils {
export function square(n: number): number {
return n * n;
}
export function sum(arr: number[]): number {
let total = 0;
for (const num of arr) {
total += num;
}
return total;
}
}
This code defines a namespace with two functions: one squares a number, the other sums an array of numbers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop inside thesumfunction that goes through each number in the array. - How many times: It runs once for every item in the input array.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The time to sum numbers grows directly with how many numbers there are. More numbers mean more additions.
Time Complexity: O(n)
This means the time to run the sum function grows in a straight line with the size of the input array.
[X] Wrong: "Using a namespace makes the code slower because it adds extra steps."
[OK] Correct: Namespaces only group code logically. They don't add loops or repeated work, so they don't change how long the code takes to run.
Understanding how code grouping like namespaces affects performance helps you write clear and efficient programs. This skill shows you can think about both organization and speed.
"What if the sum function called another function inside the loop? How would that affect the time complexity?"