我正在研究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
答案 0 :(得分:3)
当unset()释放内存时,这不会自动反映在memory_get_usage()中。内存未使用,可以重复使用;但只有在垃圾收集程序启动后,才会实际减少未使用的内存。