Enums in PHP - Time & Space Complexity
Enums in PHP help organize related values clearly. Understanding their time complexity shows how fast your program runs when using them.
We want to know how the program's speed changes when working with enums as input grows.
Analyze the time complexity of the following code snippet.
enum Status: string {
case Pending = 'pending';
case Active = 'active';
case Completed = 'completed';
}
function checkStatus(Status $status): string {
return match($status) {
Status::Pending => 'Waiting',
Status::Active => 'In progress',
Status::Completed => 'Done',
};
}
$status = Status::Active;
echo checkStatus($status);
This code defines an enum and a function that returns a message based on the enum value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
matchexpression checks enum cases once per function call. - How many times: It runs once each time
checkStatusis called.
Each call to checkStatus checks a fixed number of enum cases, no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks (one per call) |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with how many times you call the function, but each call does a fixed small amount of work.
Time Complexity: O(n)
This means the total time grows in a straight line with the number of times you use the enum in the function.
[X] Wrong: "Enums slow down the program because they check many cases every time."
[OK] Correct: The number of enum cases is fixed and small, so checking them is very fast and does not grow with input size.
Understanding how enums work and their time cost helps you write clear and efficient code, a skill valued in many programming tasks.
"What if the enum had 1000 cases? How would the time complexity of checking a case change?"