0
0
PHPprogramming~5 mins

Union types in practice in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Union types in practice
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
10About 10 type checks and simple calculations
100About 100 type checks and simple calculations
1000About 1000 type checks and simple calculations

Pattern observation: The work grows evenly with the number of inputs, doubling inputs doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly with the number of items processed.

Common Mistake

[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.

Interview Connect

Understanding how type checks affect performance helps you write clear and efficient code, a skill valued in real projects and interviews.

Self-Check

"What if the function handled an array of arrays instead of simple types? How would the time complexity change?"