Union types in practice in PHP - Time & Space Complexity
We want to see how using union types affects how long a PHP function takes to run.
Specifically, we ask: does checking multiple types slow down the code as input grows?
Analyze the time complexity of the following code snippet.
function processValue(int|string $value) {
if (is_int($value)) {
return $value * 2;
} elseif (is_string($value)) {
return strlen($value);
}
}
$inputs = [1, "hello", 3, "world"];
foreach ($inputs as $item) {
echo processValue($item) . "\n";
}
This code processes a list of values that can be either numbers or words, handling each type differently.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each item in the input array and checking its type.
- How many times: Once for each item in the array.
As the number of items grows, the function runs once per item, doing a quick type check and simple operation.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 type checks and simple calculations |
| 100 | About 100 type checks and simple calculations |
| 1000 | About 1000 type checks and simple calculations |
Pattern observation: The work grows evenly with the number of inputs, doubling inputs doubles work.
Time Complexity: O(n)
This means the time to run grows directly with the number of items processed.
[X] Wrong: "Using union types makes the function slower in a way that changes how time grows with input size."
[OK] Correct: The type checks happen once per item and are simple, so they add a small fixed cost per item, not changing the overall growth pattern.
Understanding how type checks affect performance helps you write clear and efficient code, a skill valued in real projects and interviews.
"What if the function handled an array of arrays instead of simple types? How would the time complexity change?"