0
0
Typescriptprogramming~5 mins

Enum vs union literal type trade-offs in Typescript - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Enum vs union literal type trade-offs
O(1)
Understanding Time Complexity

We want to see how using enums or union literal types affects the speed of our code.

How does the choice between these two affect how long operations take as data grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    enum ColorEnum {
      Red = "red",
      Green = "green",
      Blue = "blue"
    }

    type ColorUnion = "red" | "green" | "blue";

    function isPrimaryColorEnum(color: ColorEnum): boolean {
      return color === ColorEnum.Red || color === ColorEnum.Blue;
    }

    function isPrimaryColorUnion(color: ColorUnion): boolean {
      return color === "red" || color === "blue";
    }
    

This code checks if a color is primary using either an enum or a union literal type.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Simple equality checks in conditional statements.
  • How many times: Each check runs once per function call.
How Execution Grows With Input

Since the checks are simple comparisons, the time does not grow with input size.

Input Size (n)Approx. Operations
102 checks
1002 checks
10002 checks

Pattern observation: The number of operations per function call is constant (2 equality checks), independent of input size.

Final Time Complexity

Time Complexity: O(1)

This means each check runs in constant time, no matter the input size.

Common Mistake

[X] Wrong: "Using enums is slower because they add extra code overhead."

[OK] Correct: Both enums and union literals compile to simple values, so their runtime checks are equally fast.

Interview Connect

Understanding how different type choices affect performance helps you write clear and efficient code, a skill valued in real projects and interviews.

Self-Check

"What if we added a loop to check many colors at once? How would the time complexity change?"