Instance methods in Javascript - Time & Space Complexity
Let's see how the time it takes to run instance methods changes as we use more data.
We want to know how the work grows when calling methods on objects.
Analyze the time complexity of the following code snippet.
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count += 1;
}
incrementBy(n) {
for (let i = 0; i < n; i++) {
this.increment();
}
}
}
This code defines a class with methods to increase a count, either by 1 or by a given number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop inside
incrementBycallsincrementrepeatedly. - How many times: The loop runs
ntimes, wherenis the input toincrementBy.
Each time we increase n, the loop runs that many times, so the work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to increment |
| 100 | 100 calls to increment |
| 1000 | 1000 calls to increment |
Pattern observation: The number of operations grows evenly as n grows.
Time Complexity: O(n)
This means the time to run incrementBy grows in a straight line with the input size.
[X] Wrong: "Calling increment inside the loop makes it slower than linear time."
[OK] Correct: Each increment call is simple and constant time, so repeating it n times still grows linearly.
Understanding how instance methods run helps you explain how your code scales when working with objects and their data.
"What if incrementBy called increment twice inside the loop? How would the time complexity change?"