0
0
Typescriptprogramming~5 mins

Why typed functions matter in Typescript - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why typed functions matter
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
10About 10 additions
100About 100 additions
1000About 1000 additions

Pattern observation: The work grows directly with the number of items; double the items, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the input size.

Common Mistake

[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.

Interview Connect

Knowing how typed functions behave helps you write clear code without worrying about slowing things down.

Self-Check

"What if we changed the function to call itself recursively for each number? How would the time complexity change?"