0
0
Typescriptprogramming~5 mins

Type alias vs inline types in Typescript - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Type alias vs inline types
O(1)
Understanding Time Complexity

We want to see if using type aliases or inline types affects how long a program takes to run.

Does the way we write types change the speed of our code?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    type Point = { x: number; y: number };

    function distance(p1: Point, p2: Point): number {
      return Math.sqrt((p2.x - p1.x) ** 2 + (p2.y - p1.y) ** 2);
    }

    // Using inline types instead of alias
    function distanceInline(p1: { x: number; y: number }, p2: { x: number; y: number }): number {
      return Math.sqrt((p2.x - p1.x) ** 2 + (p2.y - p1.y) ** 2);
    }
    

This code calculates the distance between two points using either a type alias or inline types.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A fixed number of arithmetic calculations and a square root call.
  • How many times: Exactly once per function call, no loops or recursion.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
10constant steps
100constant steps
1000constant steps

Pattern observation: The work per function call is constant and does not grow with input size. Types do not affect runtime performance.

Final Time Complexity

Time Complexity: O(1)

This means the time is constant per function call, not affected by how you write the types.

Common Mistake

[X] Wrong: "Using type aliases makes the program run faster than inline types."

[OK] Correct: Types only help during coding and checking, they do not affect how fast the program runs at all.

Interview Connect

Understanding that types help with code clarity but not speed shows you know the difference between coding tools and runtime behavior.

Self-Check

"What if we added a loop inside the function that runs n times? How would the time complexity change?"