Why typed functions matter in Typescript - Performance Analysis
We want to see how using typed functions affects the speed of running code.
Does adding types change how long the program takes as input grows?
Analyze the time complexity of the following code snippet.
function sumNumbers(numbers: number[]): number {
let total = 0;
for (const num of numbers) {
total += num;
}
return total;
}
const data = [1, 2, 3, 4, 5];
sumNumbers(data);
This function adds up all numbers in an array and returns the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array once.
- How many times: Exactly once for each 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 work grows directly with the number of items; double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "Adding types makes the function slower because it checks types at runtime."
[OK] Correct: Types in TypeScript are only for development and do not add extra work when the code runs.
Knowing how typed functions behave helps you write clear code without worrying about slowing things down.
"What if we changed the function to call itself recursively for each number? How would the time complexity change?"