1

I was wondering if anyone could answer me this quick question. I tried searching it but I get similar questions but in the wrong context.

What I am wondering is take this code:

function foo()
{
    $test_array = array();
    for($i=0; $i<10000000; $i++)
    {
        $test_array[] = $i;
    }
}

What happens to $test_array after the function finishes. I know that it looses scope, I am not new to programming.

What I am wondering is should I call

unset($test_array);

before the function ends or does PHP set it for deletion to the garbage collector as the function ends?

I used the for loop just to show a variable of a fair size to get my point across.

Thanks for reading Kevin

2 Answers 2

3

Once $test_array is no longer in scope (and there are no additional references that point to it), it is flagged for garbage collection.

It ceases to be in scope when the process returns from the function to the calling routine.

So there is no need to unset it.

This would only be different if you had declared $test_array as static.

Sign up to request clarification or add additional context in comments.

3 Comments

In my own tests with memory_get_usage() (probably very platform-specific, so take with a grain of salt) -- explicitly unsetting the variable seems to free the memory right away. Letting a variable slip out of scope certainly flags the variable as available to be collected, but doesn't necessarily trigger the collector itself to come by.
unset() doesn't delete, it only flags for deletion... and garbage collection isn't triggered by unset() or by return to the calling routine. As The Coder says, it happens when the CPU has free cycles, or when PHP tries to allocate additional memory and there is insufficient for its needs.
As far as i am aware, unset does not call the garbage collector
0

unset() doesn't free the memory a variable uses, it just marks it for the garbage collector which will decide when to free the memory (when it has free cpu cycles or when it runs out of memory, whichever comes first).

However you have to realize that ALL memory used by a PHP script is freed when the script finishes which, most of the time, is measured in milliseconds, so if you're not doing any lengthy operations that would exceed the "normal" execution time of a PHP script you shouldn't worry about freeing memory.

1 Comment

I am aware that memory is freed after a script has executed, however I am a bit anal when it comes to clean, managed code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.