Augmenting third-party libraries in Typescript - Time & Space Complexity
When we add new features to existing third-party libraries, it is important to know how this affects the speed of our program.
We want to find out how the extra code changes the time it takes to run as the input grows.
Analyze the time complexity of the following code snippet.
// Adding a new method to a third-party library interface
declare module 'some-library' {
interface SomeInterface {
newMethod(): void;
}
}
// Implementation of the new method
SomeLibrary.SomeInterface.prototype.newMethod = function() {
for (let i = 0; i < this.items.length; i++) {
console.log(this.items[i]);
}
};
This code adds a new method to a library's interface that loops through an array and prints each item.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A for-loop that goes through each item in an array.
- How many times: The loop runs once for every item in the array.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 loops |
| 100 | 100 loops |
| 1000 | 1000 loops |
Pattern observation: The number of operations grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to run the new method grows in a straight line with the number of items.
[X] Wrong: "Adding a method like this does not affect performance because it's just extra code."
[OK] Correct: Even small added loops run more steps as input grows, so they do affect how long the program takes.
Understanding how your additions to existing code affect speed shows you can write code that stays fast and reliable as it grows.
"What if the new method called another method that also loops through the array? How would the time complexity change?"