Global namespace access in PHP - Time & Space Complexity
When using global namespace access in PHP, it's important to see how it affects the speed of your code.
We want to know how the time to run the code changes as the input size grows when accessing global functions or variables.
Analyze the time complexity of the following code snippet.
function sumArray(array $numbers) {
$total = 0;
foreach ($numbers as $num) {
$total += \abs($num); // global namespace function
}
return $total;
}
$values = [1, -2, 3, -4, 5];
echo sumArray($values);
This code sums the absolute values of numbers in an array using the global abs function.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element of the array and calling the global
absfunction. - How many times: Once for each element in the input array.
As the array gets bigger, the number of times we call the global function grows directly with the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to abs and 10 additions |
| 100 | 100 calls to abs and 100 additions |
| 1000 | 1000 calls to abs and 1000 additions |
Pattern observation: The work grows evenly as the input size grows.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the number of items in the array.
[X] Wrong: "Accessing a global function like abs inside a loop makes the code run slower in a way that changes the overall time complexity."
[OK] Correct: Calling a global function inside a loop adds a small fixed cost per call, but it does not change the fact that the total work still grows linearly with the input size.
Understanding how global namespace access affects time helps you explain your code's efficiency clearly and confidently in real-world coding discussions.
What if we replaced the global abs function with a custom function defined inside a namespace? How would the time complexity change?