Numeric enums in Typescript - Time & Space Complexity
We want to understand how the time it takes to work with numeric enums changes as the number of enum members grows.
Specifically, how does accessing or searching enum values behave when the enum size increases?
Analyze the time complexity of the following code snippet.
enum Colors {
Red, // 0
Green, // 1
Blue // 2
}
function getColorName(value: number): string | undefined {
return Colors[value];
}
This code defines a numeric enum and a function that looks up the name of a color by its numeric value.
- Primary operation: Direct lookup in an object (enum reverse mapping)
- How many times: Single operation per lookup, no loops or recursion
Looking up a value in the enum is like checking a label on a box directly, no matter how many boxes there are.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time to find a name does not grow with the number of enum members; it stays constant.
Time Complexity: O(1)
This means looking up a numeric enum value takes the same amount of time no matter how many items are in the enum.
[X] Wrong: "Looking up a numeric enum value takes longer as the enum gets bigger because it has to check each item."
[OK] Correct: Numeric enums in TypeScript create an object with direct keys, so the lookup is a quick direct access, not a search through all items.
Understanding how enum lookups work helps you explain efficient data access in TypeScript, showing you know how language features impact performance.
"What if we changed the enum to a string enum? How would the time complexity of looking up a name by value change?"