Union types in PHP - Time & Space Complexity
Let's explore how using union types in PHP affects the time it takes for code to run.
We want to see how the program's work changes as input grows when union types are involved.
Analyze the time complexity of the following code snippet.
function processValue(int|string $value): string {
if (is_int($value)) {
return (string)($value * 2);
} else {
return strtoupper($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, using union types to accept both.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the input array and calling
processValue. - How many times: Once for each item in the input list.
As the number of items grows, the code runs the process for each item one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 calls to processValue |
| 100 | About 100 calls to processValue |
| 1000 | About 1000 calls to processValue |
Pattern observation: The work grows directly with the number of items; doubling items doubles work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of inputs.
[X] Wrong: "Using union types makes the code slower because it checks types every time."
[OK] Correct: The type check is simple and happens once per item, so it doesn't change how the total work grows with more inputs.
Understanding how union types affect performance helps you write clear code without worrying about slowing things down as data grows.
"What if the input array was nested arrays instead of simple values? How would the time complexity change?"