PHP在函数结束后立即释放局部变量吗?

Ann*_* K. 8 php memory

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

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
Run Code Online (Sandbox Code Playgroud)

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

小智 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();
Run Code Online (Sandbox Code Playgroud)

输出:

memory before function:273312
$content size:110000
memory in function:383520
memory after function:273352
Run Code Online (Sandbox Code Playgroud)

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

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


Voi*_*cus 4

您可以在类上看到这个示例,这是因为您可以“捕获”释放类析构函数中的变量:

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();
Run Code Online (Sandbox Code Playgroud)

该脚本输出:

before b()
exit from function b()
destructor
after b()
Run Code Online (Sandbox Code Playgroud)

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