5

I have problem with the memory leak problem during the export of a large number of files from arrays of objects. Simplified code looks like this:

class Test_Class
{
    private $a = null;

    public function __construct($a = null)
    {
        $this->a = $a;
    }

    public function __destruct()
    {
        unset($this->a);
    }
}

print 'Memory before: '.memory_get_usage(1).' <br>'; // 262 144 
$a = [];
for ($i=0; $i<600000; $i++)
    $a[] = new Test_Class($i);

print 'Memory after create: '.memory_get_usage(1).' <br>'; // 129 761 280 

for($i=0; $i < count($a); $i++)
    unset($a[$i]);

unset($a);

print 'Memory after: '.memory_get_usage(1).' <br>'; // 35 389 440 

at the one of next iterations the memory still ends. Any idea how to free the memory occupied?

P.S. I try unset()/assignment null and gc_collect_cycles(), none of the methods has allowed me to release the memory occupied by the array of objects

PAN
  • 51
  • 3
  • 1
    possible duplicate of [Best way to destroy PHP object?](http://stackoverflow.com/questions/8798443/best-way-to-destroy-php-object) – Blue Jul 09 '15 at 16:24

1 Answers1

0

I don't think this is a memory leak. The memory is really freed and available, it just seems that php keep it for its use and don't give it back to the system. I would guess it has something to do with the garbage collector. It seems to be a bad behavior but maybe there is a good reason...

Her is my proof: (Because of my configuration, I used smaller values but the behavior is the same)

/*
   You class definition
*/

print 'Memory before: '.memory_get_usage(1).' <br>'; // 262 144 
$a = [];
$b = [];
for ($i=0; $i<5000; $i++)
    $a[] = new Test_Class($i);

print 'Memory after create: '.memory_get_usage(1).' <br>'; // 2 359 296 

for($i=0; $i < count($a); $i++)
    unset($a[$i]);

unset($a);

print 'Memory after unset: '.memory_get_usage(1).' <br>'; // 1 572 864 

for ($i=0; $i<1000; $i++)
    $b[] = $i;

print 'Memory after $b: '.memory_get_usage(1).' <br>'; // 1 572 864 

You can see here that the creation of $b didn't need any more memory. Which is odd because an array needs memory when you don't do anything before:

$b = [];

print 'Memory before: '.memory_get_usage(1).' <br>'; // 262 144 

for ($i=0; $i<1000; $i++)
    $b[] = $i;

print 'Memory after: '.memory_get_usage(1).' <br>'; // 524 288 

That why I think the memory is freed but php just sits on it.

Xetolone
  • 357
  • 1
  • 12