Namespace merging in Typescript - Time & Space Complexity
When we use namespace merging in TypeScript, we combine multiple pieces of code under one name.
We want to see how the time to process this merging grows as the code size grows.
Analyze the time complexity of the following code snippet.
namespace Animals {
export function speak() { console.log("Animal speaks"); }
}
namespace Animals {
export function run() { console.log("Animal runs"); }
}
Animals.speak();
Animals.run();
This code merges two namespaces named Animals and calls their functions.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The compiler processes each namespace block to merge their contents.
- How many times: Once for each namespace declaration with the same name.
As the number of namespace blocks with the same name grows, the compiler merges more pieces together.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 merge steps |
| 100 | About 100 merge steps |
| 1000 | About 1000 merge steps |
Pattern observation: The work grows directly with the number of namespace parts to merge.
Time Complexity: O(n)
This means the time to merge namespaces grows in a straight line as you add more parts.
[X] Wrong: "Merging namespaces happens instantly no matter how many parts there are."
[OK] Correct: Each namespace part must be processed, so more parts mean more work and more time.
Understanding how merging works helps you explain how your code scales and how the compiler handles your code structure.
"What if we nested namespaces inside each other instead of merging at the same level? How would the time complexity change?"