0
0
PHPprogramming~5 mins

Union types in PHP - Time & Space Complexity

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

Scenario Under Consideration

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

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

As the number of items grows, the code runs the process for each item one by one.

Input Size (n)Approx. Operations
10About 10 calls to processValue
100About 100 calls to processValue
1000About 1000 calls to processValue

Pattern observation: The work grows directly with the number of items; doubling items doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the number of inputs.

Common Mistake

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

Interview Connect

Understanding how union types affect performance helps you write clear code without worrying about slowing things down as data grows.

Self-Check

"What if the input array was nested arrays instead of simple values? How would the time complexity change?"