8

该代码更好地说明了我的要求:

function foo(){

  $var = get_huge_amount_of_data();

  return $var[0];
}


$s = foo();

// is memory freed here for the $var variable created above?

do_other_stuff(); // need memory here lol

所以我知道 $var 在某些时候会被释放,但是 PHP 能有效地做到这一点吗?或者我是否需要手动取消设置昂贵的变量?

4

4 回答 4

8

是的,它确实被释放了。

您可以使用以下方法进行检查:

function a() {
    $var = "Hello World";
    $content = "";
    for ($i = 0; $i < 10000; $i++) {
        $content .= $var;
    }
    print '<br>$content size:'.strlen($content);
    print '<br>memory in function:'.memory_get_usage();
    return null;
}

print '<br>memory before function:'.memory_get_usage();
a();
print '<br>memory after function:'.memory_get_usage();

输出:

memory before function:273312
$content size:110000
memory in function:383520
memory after function:273352

在函数 PHP 使用 273312 字节之前。
在函数完成之前,我们再次检查了内存使用情况,它使用了 383520。
我们检查了 $content 的大小,即 110000 字节。
273312 + 110000 = 383312
剩下的 208 字节来自其他变量(我们只计算了 $content)
函数完成后,我们再次检查内存使用情况,它恢复到(几乎(40 字节差异))和之前一样.

40 字节的差异很可能是函数声明和 for 循环声明。

于 2015-04-01T18:42:05.290 回答
3

你可以在一个类上看到这个例子,那是因为你可以在类的析构函数中“捕捉”释放一个变量:

class a {
  function __destruct(){
    echo "destructor<br>";
  }
}

function b(){ // test function
  $c=new a();
  echo 'exit from function b()<br>';
}

echo "before b()<br>";
b();
echo "after b()<br>";

die();

该脚本输出:

before b()
exit from function b()
destructor
after b()

所以现在很清楚,变量在函数退出时被销毁。

于 2013-03-26T20:02:46.320 回答
2

所以我知道 $var 在某些时候会被释放,但是 PHP 能有效地做到这一点吗?或者我是否需要手动取消设置昂贵的变量?

是的,PHP 做得很好。这是一个你永远不需要考虑的问题。在您的情况下,我宁愿考虑 and 之间的时刻$var = ..return ..因为那是您无法避免内存消耗的时刻。您应该尝试找到一个解决方案,您不需要通过get_huge_amount_of_data()然后选择单个项目来获取整个数据集,而只需要您需要的数据。

于 2012-12-29T15:14:40.870 回答
2

是的,这是因为$var它在堆栈上声明并在超出范围后立即清除

你可以参考这个https://stackoverflow.com/a/5971224/307157

于 2012-12-29T15:02:46.567 回答