1

我想知道是否有人可以回答我这个快速的问题。我尝试搜索它,但我得到了类似的问题,但在错误的上下文中。

我想知道的是使用以下代码:

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

函数完成后 $test_array 会发生什么。我知道它失去了范围,我对编程并不陌生。

我想知道的是我应该打电话

unset($test_array);

在函数结束之前或 PHP 是否将其设置为在函数结束时将其删除到垃圾收集器?

我使用 for 循环只是为了显示一个大小合适的变量来表达我的观点。

感谢阅读凯文

4

2 回答 2

3

一旦$test_array不再在范围内(并且没有其他指向它的引用),它就会被标记为垃圾回收。

当进程从函数返回到调用例程时,它不再在范围内。

So there is no need to unset it.

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

于 2012-03-02T20:59:25.753 回答
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.

于 2012-03-02T21:09:46.713 回答