I am studying PHP memory management and running a few code samples. The output of this code
class Person
{
public function sayHello($who)
{
echo "Hello, $who!", "
";
}
}
echo "Start: ", memory_get_usage(), "
";
$person = new Person();
echo "Person object: ", memory_get_usage(), "
";
$person->sayHello("World");
echo "After call: ", memory_get_usage(), "
";
unset($person);
echo "After unset: ", memory_get_usage(), "
";
is:
Start: 122000
Person object: 122096
Hello, World!
After call: 122096
After unset: 122000
as expected. After allocating an object the memory grows, but after a method call ends and the object is unset, it returns to normal. Now if I modify the code like this:
class Person
{
public function sayHello($who)
{
echo "During call: ", memory_get_usage(), "
";
echo "Hello, $who!", "
";
}
}
echo "Start: ", memory_get_usage(), "
";
$person = new Person();
echo "Person object: ", memory_get_usage(), "
";
$person->sayHello("World");
echo "After call: ", memory_get_usage(), "
";
unset($person);
echo "After unset: ", memory_get_usage(), "
";
I get:
Start: 122268
Person object: 122364
During call: 122408
Hello, World!
After call: 122380
After unset: 122284
Why I can't free up all the memory I used? I'm using 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
When memory is released by unset(), this is not automatically reflected in memory_get_usage(). The memory is unused, and is available for reuse; but it is only after the garbage collection routines kick in that unused memory is actually reduced.