Class syntax in Javascript - Time & Space Complexity
Let's see how the time it takes to run code using JavaScript classes changes as we create more objects or call methods.
We want to know how the work grows when using class syntax for multiple objects.
Analyze the time complexity of the following code snippet.
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count++;
}
}
const counters = [];
for (let i = 0; i < n; i++) {
counters.push(new Counter());
}
This code creates n Counter objects, each starting with a count of zero.
- Primary operation: Creating a new Counter object inside a loop.
- How many times: The loop runs
ntimes, creatingnobjects.
Each time we increase n, we create more objects, so the work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations |
| 100 | 100 object creations |
| 1000 | 1000 object creations |
Pattern observation: The work grows evenly as we add more objects.
Time Complexity: O(n)
This means the time to create all objects grows in a straight line as we add more objects.
[X] Wrong: "Creating objects inside a loop is instant and does not depend on how many objects we make."
[OK] Correct: Each object takes some time to create, so more objects mean more total time.
Understanding how creating many objects affects time helps you write efficient code and explain your choices clearly.
"What if the increment method was called inside the loop for each object? How would the time complexity change?"