Why generic interfaces matter in Typescript - Performance Analysis
When using generic interfaces, it is important to understand how the time to process data changes as the input grows.
We want to know how the code's speed changes when the size of the data inside the generic interface increases.
Analyze the time complexity of the following code snippet.
interface Box<T> {
items: T[];
add(item: T): void;
get(index: number): T | undefined;
}
class SimpleBox<T> implements Box<T> {
items: T[] = [];
add(item: T) { this.items.push(item); }
get(index: number) { return this.items[index]; }
}
This code defines a generic interface and a class that stores items in an array and allows adding and getting items by index.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding an item uses array push (constant time), getting an item accesses array by index (constant time).
- How many times: Each add or get operation happens once per call, no loops inside these methods.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 adds = 10 operations, 10 gets = 10 operations |
| 100 | 100 adds = 100 operations, 100 gets = 100 operations |
| 1000 | 1000 adds = 1000 operations, 1000 gets = 1000 operations |
Pattern observation: Each add or get operation takes about the same time regardless of how many items are stored.
Time Complexity: O(1)
This means adding or getting an item takes the same amount of time no matter how many items are in the generic interface.
[X] Wrong: "Using a generic interface makes adding or getting items slower because it adds extra work."
[OK] Correct: The generic interface only describes the shape of data; it does not add extra steps when running the code. The actual operations depend on the data structure used, not on generics.
Understanding how generic interfaces affect performance helps you explain your design choices clearly and confidently in real projects and interviews.
"What if the get method searched the array for a matching item instead of using an index? How would the time complexity change?"