0
0
Typescriptprogramming~5 mins

Declaring functions and classes in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Declaring functions and classes
O(n)
Understanding Time 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?

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The forEach loop that calls sayHello on each person.
  • How many times: Once for each person in the people array.
How Execution Grows With Input

Each person in the list causes one call to sayHello, which calls greet.

Input Size (n)Approx. Operations
1010 calls to sayHello and greet
100100 calls to sayHello and greet
10001000 calls to sayHello and greet

Pattern observation: The number of calls grows directly with the number of people.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as you add more people.

Common Mistake

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

Interview Connect

Understanding how function and class declarations affect performance helps you write clear and efficient code, a skill valued in many coding challenges.

Self-Check

"What if we created 1000 objects but only called sayHello on 10 of them? How would the time complexity change?"