Enum member access in Typescript - Time & Space Complexity
Let's see how fast we can get values from an enum in TypeScript.
We want to know how the time to access enum members changes as the enum grows.
Analyze the time complexity of the following code snippet.
enum Colors {
Red,
Green,
Blue,
Yellow,
Purple
}
const colorName = Colors[2];
This code gets the name of the color with the number 2 from the enum.
- Primary operation: Direct lookup of enum member by key.
- How many times: Only once per access, no loops or repeated steps.
Getting a value from an enum is like looking up a word in a dictionary.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time to access an enum member stays the same no matter how many members there are.
Time Complexity: O(1)
This means accessing an enum member takes the same short time, even if the enum is very big.
[X] Wrong: "Accessing an enum member takes longer if the enum has more members."
[OK] Correct: Enum members are stored like keys in a map, so access is direct and fast regardless of size.
Knowing that enum access is quick helps you explain how your code handles fixed sets of values efficiently.
"What if we used a function to search for a value inside an enum instead of direct access? How would the time complexity change?"