[分享] PHP GC 機制
題外話: 搞了好久終於註冊好 PTT 了。
======================================
前陣子看到某篇文章提到,要回收物件時,
使用 $obj = null 會馬上回收,unset($obj) 則會比較慢。
在解答之前,先來玩個小遊戲。
<?php
class test
{
public function __destruct()
{
echo "object of test is dead\n";
}
}
$test = new test();
$test = null;
die("program is end\n");
執行結果
object of test is dead
program is end
很符合結果 $test = null 先執行 GC (destruct) 接著 die output
===================
<?php
class test
{
protected $me;
public function __contruct()
{
$this-> me = $this;
}
public function __destruct()
{
echo "object of test is dead\n";
}
}
$test = new test();
unset($test);
die("program is end\n");
執行結果
program is end
object of test is dead
unset 沒有進行 GC,一直到程式結束後,才開始進行 GC。
疑 unset 沒有進行 GC ??!!
好玩的事情發生了,難道真的是 unset 是看心情 GC 的??
其實上面的範例即使改成 $test = null; 執行結果也是一樣的。
這邊就先賣個關子,明天再來解答為什麼會有這個結果,以及該怎麼避免這樣的問題。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.130.136.115
→
06/03 21:08, , 1F
06/03 21:08, 1F
→
06/03 23:29, , 2F
06/03 23:29, 2F
討論串 (同標題文章)
PHP 近期熱門文章
PTT數位生活區 即時熱門文章
5
22