Super keyword behavior in Typescript - Time & Space Complexity
Let's explore how using the super keyword affects the time it takes for a program to run.
We want to know how calling methods from a parent class scales as our program grows.
Analyze the time complexity of the following code snippet.
class Animal {
speak() {
console.log('Animal speaks');
}
}
class Dog extends Animal {
speak() {
super.speak();
console.log('Dog barks');
}
}
const dog = new Dog();
dog.speak();
This code shows a class Dog that calls its parent Animal method using super.speak().
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling
super.speak()inside theDogclass method. - How many times: Exactly once per
dog.speak()call.
Since super.speak() calls a single parent method, the work done does not increase with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls, each calls super.speak() once |
| 100 | 100 calls, each calls super.speak() once |
| 1000 | 1000 calls, each calls super.speak() once |
Pattern observation: The number of operations grows directly with how many times the method is called, but each call does a fixed amount of work.
Time Complexity: O(n)
This means the total time grows linearly with how many times you call the method, but each call itself is simple and constant time.
[X] Wrong: "Using super makes the method slower by a lot because it calls another method."
[OK] Correct: Calling super just runs one extra method, which is a fixed cost and does not multiply with input size inside that call.
Understanding how super works helps you explain class inheritance clearly and shows you know how method calls affect performance in real code.
"What if the parent method called by super itself called another method multiple times? How would that affect the time complexity?"