PHP: array of objects and memory leak

I have a problem with a memory leak problem when exporting a large number of files from arrays of objects. The simplified code is as follows:

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 

in one of the following iterations, the memory is still running out. Any idea how to free up busy memory?

PS I'm trying to do unset () / null assignment and gc_collect_cycles (), none of the methods allowed me to free the memory occupied by an array of objects

+5
source share
1 answer

I do not think this is a memory leak. The memory is really freed and available, it just seems that php saves it for its use and does not return it to the system. I would suggest that this has anything to do with the garbage collector. This seems to be bad behavior, but maybe there is a good reason ...

This is my proof: (Due to my configuration, I used lower values, but the behavior was 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 

Here you can see that no more memory is needed to create $b . Which is strange, because an array needs memory when you do nothing 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 

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

0
source

All Articles