Nullable types in functions in PHP - Time & Space Complexity
We want to see how using nullable types in functions affects the time it takes to run the code.
Does allowing a value to be null change how long the function takes to finish?
Analyze the time complexity of the following code snippet.
function processValue(?int $value): int {
if ($value === null) {
return 0;
}
return $value * 2;
}
$result = processValue(10);
$resultNull = processValue(null);
This function takes an integer or null, checks if it is null, and returns a result accordingly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: There are no loops or repeated steps; just a simple check and calculation.
- How many times: The function runs once per call, doing a fixed number of steps.
The function does the same small number of steps no matter what number or null you give it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 3 steps |
| 100 | 3 steps |
| 1000 | 3 steps |
Pattern observation: The number of steps stays the same no matter the input size.
Time Complexity: O(1)
This means the function takes the same short time to run no matter what input it gets.
[X] Wrong: "Nullable types make the function slower because it has to check for null every time."
[OK] Correct: The null check is just one simple step and does not grow with input size, so it does not slow down the function noticeably.
Understanding how simple checks like nullable types affect performance helps you explain your code clearly and shows you think about efficiency, which is a great skill to have.
"What if the function processed an array of nullable integers instead of a single nullable integer? How would the time complexity change?"