0
0
Typescriptprogramming~5 mins

Why typed classes matter in Typescript - Performance Analysis

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

When using typed classes in TypeScript, it is important to understand how the program's work grows as the input changes.

We want to see how the time to create and use typed classes changes when we have more data or objects.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class User {
  constructor(public id: number, public name: string) {}
}

function createUsers(n: number): User[] {
  const users: User[] = [];
  for (let i = 0; i < n; i++) {
    users.push(new User(i, `User${i}`));
  }
  return users;
}
    

This code creates an array of typed User objects, each with an id and name, for n users.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop creating and adding User objects to the array.
  • How many times: Exactly n times, once for each user.
How Execution Grows With Input

As n grows, the number of User objects created and added grows directly with n.

Input Size (n)Approx. Operations
10About 10 User creations and insertions
100About 100 User creations and insertions
1000About 1000 User creations and insertions

Pattern observation: The work grows evenly and directly as n increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to create and store users grows in a straight line with the number of users.

Common Mistake

[X] Wrong: "Typed classes make the code slower because of extra type checks at runtime."

[OK] Correct: TypeScript types are removed when the code runs, so typed classes do not add runtime cost. The time depends on how many objects you create, not the types.

Interview Connect

Understanding how typed classes affect time helps you explain how your code scales and why types are safe without slowing down your program.

Self-Check

"What if we added a nested loop inside the createUsers function to assign friends to each user? How would the time complexity change?"