Generic function syntax in Typescript - Time & Space Complexity
We want to see how the time it takes to run a generic function changes as the input size grows.
How does the function's work increase when we give it bigger inputs?
Analyze the time complexity of the following code snippet.
function identity<T>(items: T[]): T[] {
return items.map(item => item);
}
const numbers = [1, 2, 3, 4, 5];
const result = identity(numbers);
This function takes an array of any type and returns a new array with the same items.
- Primary operation: The
mapmethod loops through each item in the array. - How many times: Once for every item in the input array.
As the input array gets bigger, the function does more work by visiting each item once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
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: "Generic functions are slower because they handle any type."
[OK] Correct: The generic part only affects types at compile time, not how many steps the function takes at run time.
Understanding how generic functions behave helps you explain your code clearly and shows you know how input size affects performance.
What if we changed the function to use a nested loop inside the map? How would the time complexity change?