0
0
PHPprogramming~5 mins

Script execution and memory reset in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Script execution and memory reset
O(n)
Understanding Time 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.

Scenario Under Consideration

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

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

As the array gets bigger, the loop runs more times, so the work grows with the number of items.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with the input size; double the input, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the script grows in a straight line with the size of the input array.

Common Mistake

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

Interview Connect

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.

Self-Check

"What if we changed the function to call itself recursively instead of using a loop? How would the time complexity change?"