Type alias vs inline types in Typescript - Performance Comparison
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?
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 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.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | constant steps |
| 100 | constant steps |
| 1000 | constant steps |
Pattern observation: The work per function call is constant and does not grow with input size. Types do not affect runtime performance.
Time Complexity: O(1)
This means the time is constant per function call, not affected by how you write the types.
[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.
Understanding that types help with code clarity but not speed shows you know the difference between coding tools and runtime behavior.
"What if we added a loop inside the function that runs n times? How would the time complexity change?"