Enum vs union literal type trade-offs in Typescript - Performance Comparison
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?
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 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.
Since the checks are simple comparisons, the time does not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 2 checks |
| 100 | 2 checks |
| 1000 | 2 checks |
Pattern observation: The number of operations per function call is constant (2 equality checks), independent of input size.
Time Complexity: O(1)
This means each check runs in constant time, no matter the input size.
[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.
Understanding how different type choices affect performance helps you write clear and efficient code, a skill valued in real projects and interviews.
"What if we added a loop to check many colors at once? How would the time complexity change?"