3

我正在研究 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";

是:

Start: 122000
Person object: 122096
Hello, World!
After call: 122096
After unset: 122000

正如预期的那样。分配对象后,内存会增长,但在方法调用结束并且对象未设置后,它会恢复正常。现在,如果我像这样修改代码:

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
4

1 回答 1

3

当 unset() 释放内存时,这不会自动反映在 memory_get_usage() 中。内存未使用,可重复使用;但只有在垃圾收集程序启动后,未使用的内存才会真正减少。

于 2012-12-16T17:37:17.503 回答