views:

169

answers:

3

Hi,

I'm trying to avoid the memory leak in PHP. When I create a object and unset it at the end it's still in memory. The unset looks like:

$obj = NULL;
unset($obj);

Still this will not help.

My question is what will happen when I fork the proccess and the object will be created and destructed in the child thread? Will this be the same? Or is there any other way how the free the memory?

This is the import script which will consume few gigs of ram.

+3  A: 

No need to set the variable to NULL before calling unset() on it. Note however that unset() does not force memory to be freed. The main thing you may want to check is that your object clears any references it has to large chunks of data before you unset it.

Amber
+8  A: 

PHP 5.3 has a garbage collector that can collect cyclic references. It might be worth it to try:

gc_enable();

class A {
  public function __construct() {
    $this->data = str_repeat("A", 1024000);
  }
}

$mem = memory_get_usage();
$a = new A();
$mem2 = memory_get_usage();
$a->a = $a;
$a->a->mydata =  $a->data . 'test';
$mem3 = memory_get_usage();
unset($a);
gc_collect_cycles();
$mem4 = memory_get_usage();      

printf("MEM 1 at start %0.2f Mb\n", ($mem / 1024) / 1024);
printf("MEM 2 after first instantiation %0.2f Mb\n", ($mem2 / 1024) / 1024);
printf("MEM 3 after self-ref: %0.2f Mb\n", ($mem3 / 1024) / 1024);
printf("MEM 4 after unset(\$a): %0.2f Mb\n", ($mem4 / 1024) / 1024);

Output:

MEM 1 at start: 0.31 Mb
MEM 2 after first instantiation: 1.29 Mb
MEM 3 after self-ref: 2.26 Mb
MEM 4 after unset($a): 0.31 Mb
MathieuK
+1, nice example data
Paul Dixon
+1  A: 

well your import script should not use a few gigs of ram in the first place. try to store the big chunks of data in another place (filesystem or DB) when you don't absolutely need it. Also think about importing smaller sections at a time, not all in one big chunk, even if it will take longer to process, but this way you will tradeoff the big memory consumption.

What your'e talking about is not a memory leak, as this is a documented,wel known behavior. As MathieuK said, in PHP5.3 you may use some gc* functions but i've never tested them. PHP is a pretty bad language to use for handling temporary big chunks of data, because after an allocation, the allocated memory will never get free'd again, even if you unset it(this is because the allocated memory will get reused, and this is a good thing in a web page, but not a good thing in a large "hardcore" script..).

Quamis