views:

2099

answers:

2

A basic dummy class:

class foo
{
    var $bar = 0;
    function foo() {}
    function boo() {}
}
echo memory_get_usage();
echo "\n";
$foo = new foo();
echo memory_get_usage();
echo "\n";
unset($foo);
echo memory_get_usage();
echo "\n";
$foo = null; 
echo memory_get_usage();
echo "\n";

Outputs:

$ php test.php
353672
353792
353792
353792

Now, I know that PHP docs say that memory won't be freed until it is needed (hitting the ceiling). However, I wrote this up as a small test, because I've got a much longer task, using a much bigger object, with many instances of that object. And the memory just climbs, eventually running out and stopping execution. Even though these large objects do take up memory, since I destroy them after I'm done with each one (serially), it should not run out of memory (unless a single object exhausts the entire space for memory, which is not the case).

Thoughts?

+2  A: 

Do you have any circular references that could stop the garbage collector from doing its task?

I ran a quick test creating 1,000,000 objects and the memory wasn't eaten up:

class foo
{
    var $bar = 0;
    function foo() {}
    function boo() {}
}

echo memory_get_usage() . "\n";

$foo = new foo();
unset($foo);

echo memory_get_usage() . "\n";

for ($i = 0; $i < 1000000; $i++)
{
 $var = 'foo' . $i; // Use a different variable name each time
 $$var = new foo();
 unset($$var);
}

echo memory_get_usage() . "\n";

65080 65384 65568 <-- A very tiny increase for 1,000,000 objects created and destroyed

Greg
On 5.2.8 on Windows I got 62360 62528 62712 which was even smaller :)
TravisO
+2  A: 

PHP's support for objects & classes aren't very efficient in ver 5.2 (nor have they been in the past), but the upcoming 5.3 and 6.0 are a big overhaul in regards to class and object usage and you will see speed and memory improvements in them both.

I have also written some bare bone frameworks in PHP 5.2.x and found the memory usage surprising bloated also. Although considering how cheap powerful multi-core CPUs are and ram is, I would say keep coding in a manner that makes the most sense to you and creates a more RAD setup.

If using Smarty or Drupal makes your work project finish faster, then use them, or whatever custom stuff you do. Don't let today's poor memory/speed usage turn you off to OOP or frameworks because tomorrow's version has some noteworthy improvements (real world benchmarks have shown a 30% speed improvement on the same code).

PS: There's something wrong with your setup, I ran the same code on Apache /w PHP 5.2.8 on Windows XP and got: 60872 61080 61080 61080

TravisO