Declaring functions and classes in Typescript - Time & Space Complexity
When we declare functions or classes, we want to know how much time it takes to create them as the program grows.
We ask: Does making more functions or classes slow down the program, and by how much?
Analyze the time complexity of the following code snippet.
function greet(name: string) {
return `Hello, ${name}!`;
}
class Person {
constructor(public name: string) {}
sayHello() {
return greet(this.name);
}
}
const people = [new Person('Alice'), new Person('Bob')];
people.forEach(p => console.log(p.sayHello()));
This code declares a function and a class, creates two objects, and calls a method on each.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forEachloop that callssayHelloon each person. - How many times: Once for each person in the
peoplearray.
Each person in the list causes one call to sayHello, which calls greet.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to sayHello and greet |
| 100 | 100 calls to sayHello and greet |
| 1000 | 1000 calls to sayHello and greet |
Pattern observation: The number of calls grows directly with the number of people.
Time Complexity: O(n)
This means the time to run grows in a straight line as you add more people.
[X] Wrong: "Declaring a function or class takes a lot of time every time it is used."
[OK] Correct: Declaring happens once when the code loads, not each time you call the function or create an object.
Understanding how function and class declarations affect performance helps you write clear and efficient code, a skill valued in many coding challenges.
"What if we created 1000 objects but only called sayHello on 10 of them? How would the time complexity change?"