Enums in Blockchain / Solidity - Time & Space Complexity
Enums help organize related values in blockchain code. Understanding their time complexity shows how fast operations with enums run as the program grows.
We want to know how the time to use enums changes when we work with more data.
Analyze the time complexity of the following code snippet.
enum Status {
Pending,
Confirmed,
Failed
}
function checkStatus(Status current) public pure returns (string memory) {
if (current == Status.Pending) {
return "Waiting";
} else if (current == Status.Confirmed) {
return "Success";
} else {
return "Error";
}
}
This code defines an enum with three states and a function that checks the current state to return a message.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Simple if-else checks comparing enum values.
- How many times: Each call runs these checks once, no loops or recursion.
Checking an enum value takes the same steps no matter how many enum options exist.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 (enum states) | 3 checks max |
| 10 (if more states) | 10 checks max |
| 100 (many states) | 100 checks max |
Pattern observation: The number of checks grows directly with the number of enum states.
Time Complexity: O(n)
This means the time to check an enum grows linearly with the number of enum options.
[X] Wrong: "Enums always take constant time to check because they are simple values."
[OK] Correct: If you check enums with many if-else statements, the time grows with the number of options, not constant.
Knowing how enum checks scale helps you write clear and efficient blockchain code. It shows you understand how small design choices affect speed.
"What if we replaced the if-else chain with a mapping from enum to string? How would the time complexity change?"