PHP memory leak and fork

memory-leaks, php

Solution

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   

Problem

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.

Original source