Why classes are introduced in Javascript - Performance Analysis
We want to understand how using classes affects the time it takes for JavaScript code to run.
Specifically, we ask: does introducing classes change how the program's work grows as input grows?
Analyze the time complexity of the following code snippet.
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, ${this.name}!`;
}
}
const people = [];
for (let i = 0; i < n; i++) {
people.push(new Person(`Person ${i}`));
}
This code creates n Person objects and stores them in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop creating new Person objects.
- How many times: Exactly n times, once per loop iteration.
As n grows, the number of Person objects created grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations |
| 100 | 100 object creations |
| 1000 | 1000 object creations |
Pattern observation: The work grows directly with n, doubling n doubles the work.
Time Complexity: O(n)
This means the time to create all objects grows in a straight line as the number of objects increases.
[X] Wrong: "Using classes makes the code slower because of extra overhead."
[OK] Correct: Creating objects with classes still takes time proportional to how many objects you make, just like plain objects. The class syntax does not add hidden loops or repeated work.
Understanding how classes affect time helps you explain your code choices clearly and shows you know how code structure relates to performance.
"What if we added a method inside the loop that does another loop over a fixed-size array? How would the time complexity change?"