0
0
PHPprogramming~5 mins

Destructor method in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Destructor method
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run a destructor method changes as the program runs.

Specifically, how does the destructor's work grow when objects are destroyed?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Example {
    public function __destruct() {
        echo "Cleaning up...\n";
    }
}

$objects = [];
for ($i = 0; $i < 5; $i++) {
    $objects[] = new Example();
}
// Objects are destroyed automatically at script end
    

This code creates 5 objects, each with a destructor that runs when the object is destroyed.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The destructor method runs once for each object destroyed.
  • How many times: It runs exactly as many times as there are objects created (5 times here).
How Execution Grows With Input

Each new object adds one destructor call when it is destroyed.

Input Size (n)Approx. Operations
1010 destructor calls
100100 destructor calls
10001000 destructor calls

Pattern observation: The number of destructor calls grows directly with the number of objects.

Final Time Complexity

Time Complexity: O(n)

This means the time to run all destructors grows in a straight line as the number of objects increases.

Common Mistake

[X] Wrong: "The destructor runs only once no matter how many objects exist."

[OK] Correct: Each object has its own destructor call, so more objects mean more destructor executions.

Interview Connect

Understanding how destructors work helps you reason about cleanup tasks and resource management in real programs.

Self-Check

"What if the destructor method contained a loop that processed an array of size m? How would the time complexity change?"