Why global state is dangerous in PHP - Performance Analysis
When using global state in PHP, it's important to see how it affects the program's behavior as it grows.
We want to understand how accessing and changing global variables impacts the program's speed and complexity.
Analyze the time complexity of the following code snippet.
<?php
$globalArray = [];
function addItem($item) {
global $globalArray;
$globalArray[] = $item;
}
for ($i = 0; $i < $n; $i++) {
addItem($i);
}
This code adds items to a global array inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding an item to the global array inside the loop.
- How many times: The loop runs
ntimes, so the add operation repeatsntimes.
Each new item is added one by one, so the total work grows as we add more items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions to the global array |
| 100 | 100 additions to the global array |
| 1000 | 1000 additions to the global array |
Pattern observation: The number of operations grows directly with the input size.
Time Complexity: O(n)
This means the time to complete the task grows in a straight line as the input size increases.
[X] Wrong: "Using global variables makes the code faster because data is always available."
[OK] Correct: Accessing and modifying global state can cause hidden delays and bugs, especially as the program grows, making it harder to predict performance.
Understanding how global state affects program growth helps you write clearer, more predictable code, a skill valued in many coding challenges and real projects.
"What if we replaced the global array with a local array passed as a function argument? How would the time complexity change?"