2012-12-16 44 views
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 
+0

試圖在unsetting後再次創建類Person的對象,然後您將看到php如何重用內存;) – meze

+0

嘗試相同的測試,並添加memory_get_usage(true)以獲得真實用法... – matteosister

回答

3

當存儲器被複位()釋放,這不是自動反映在memory_get_usage()。內存未使用,可供重用;但是隻有在垃圾收集例程開始之後,實際上減少了未使用的內存。

+0

「未使用的內存實際上減少了「 - 我聽說在某個地方,減少堆是不容易的,由於碎片和PHP從來沒有這樣做,直到腳本被終止。 – meze