3
我正在學習PHP內存管理並運行一些代碼示例。 此代碼PHP在這種情況下泄漏內存嗎?
class Person
{
public function sayHello($who)
{
echo "Hello, $who!", "\n";
}
}
echo "Start: ", memory_get_usage(), "\n";
$person = new Person();
echo "Person object: ", memory_get_usage(), "\n";
$person->sayHello("World");
echo "After call: ", memory_get_usage(), "\n";
unset($person);
echo "After unset: ", memory_get_usage(), "\n";
的輸出是:
如預期。分配一個對象後,內存會增長,但在方法調用結束並且對象未設置後,它將恢復正常。 現在,如果我修改這樣的代碼:
class Person
{
public function sayHello($who)
{
echo "During call: ", memory_get_usage(), "\n";
echo "Hello, $who!", "\n";
}
}
echo "Start: ", memory_get_usage(), "\n";
$person = new Person();
echo "Person object: ", memory_get_usage(), "\n";
$person->sayHello("World");
echo "After call: ", memory_get_usage(), "\n";
unset($person);
echo "After unset: ", memory_get_usage(), "\n";
我得到:
Start: 122268
Person object: 122364
During call: 122408
Hello, World!
After call: 122380
After unset: 122284
爲什麼我不能釋放我用了所有的記憶? 我使用PHP 5.4:
PHP 5.4.9-4~oneiric+1 (cli) (built: Nov 30 2012 10:46:16)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies
with Xdebug v2.2.1, Copyright (c) 2002-2012, by Derick Rethans
試圖在unsetting後再次創建類Person的對象,然後您將看到php如何重用內存;) – meze
嘗試相同的測試,並添加memory_get_usage(true)以獲得真實用法... – matteosister