0
0
Javascriptprogramming~5 mins

Why classes are introduced in Javascript - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why classes are introduced
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As n grows, the number of Person objects created grows the same way.

Input Size (n)Approx. Operations
1010 object creations
100100 object creations
10001000 object creations

Pattern observation: The work grows directly with n, doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to create all objects grows in a straight line as the number of objects increases.

Common Mistake

[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.

Interview Connect

Understanding how classes affect time helps you explain your code choices clearly and shows you know how code structure relates to performance.

Self-Check

"What if we added a method inside the loop that does another loop over a fixed-size array? How would the time complexity change?"