Why typed classes matter in Typescript - Performance Analysis
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.
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 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.
As n grows, the number of User objects created and added grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 User creations and insertions |
| 100 | About 100 User creations and insertions |
| 1000 | About 1000 User creations and insertions |
Pattern observation: The work grows evenly and directly as n increases.
Time Complexity: O(n)
This means the time to create and store users grows in a straight line with the number of users.
[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.
Understanding how typed classes affect time helps you explain how your code scales and why types are safe without slowing down your program.
"What if we added a nested loop inside the createUsers function to assign friends to each user? How would the time complexity change?"