Script execution and memory reset in PHP - Time & Space Complexity
When a PHP script runs, it starts fresh each time. This means memory and variables reset with every run.
We want to understand how this reset affects the time it takes to run the script as input grows.
Analyze the time complexity of the following code snippet.
<?php
function processData(array $data) {
$sum = 0;
foreach ($data as $value) {
$sum += $value;
}
return $sum;
}
$input = range(1, 1000);
echo processData($input);
?>
This code sums all numbers in an array each time the script runs, starting fresh every time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array to add each number.
- How many times: Once per script run, exactly as many times as there are items in the array.
As the array gets bigger, the loop runs more times, so the work grows with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the input size; double the input, double the work.
Time Complexity: O(n)
This means the time to run the script grows in a straight line with the size of the input array.
[X] Wrong: "Since the script resets memory each time, the time to run stays the same no matter the input size."
[OK] Correct: Even though memory resets, the script still has to do work for every item in the input each run, so bigger input means more work and more time.
Understanding how script execution resets memory helps you explain how PHP handles each request fresh, which is key for writing efficient code that scales well.
"What if we changed the function to call itself recursively instead of using a loop? How would the time complexity change?"