Why understanding the boundary matters in Typescript - Performance Analysis
When we write code, knowing how long it takes to run helps us make better choices. Understanding boundaries means seeing how the code behaves at the edges of input sizes.
We want to know: how does the program's work grow when inputs get very big or very small?
Analyze the time complexity of the following code snippet.
function sumUpTo(n: number): number {
let total = 0;
for (let i = 1; i <= n; i++) {
total += i;
}
return total;
}
This code adds all numbers from 1 up to n and returns the total sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that adds numbers from 1 to n.
- How many times: It runs exactly n times, once for each number.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: As n grows, the number of additions grows in the same way, one for each number.
Time Complexity: O(n)
This means the time to finish grows directly with the size of the input n.
[X] Wrong: "The loop runs fewer times because it stops early sometimes."
[OK] Correct: The loop always runs from 1 to n without skipping, so it always does n steps.
Understanding how loops grow with input size is a key skill. It helps you explain your code clearly and shows you can think about efficiency, which is important in real projects.
"What if we changed the loop to run only up to n/2? How would the time complexity change?"