Description
Jira issue originally created by user Emiel:
When the hydrator iterate() function is invoked, a new event is added to the event manager with a reference to the current hydrator object. This reference is never cleared which causes the hydrator object to never be cleared from memory by the PHP garbage collection.
$evm = $this->_em->getEventManager();
$evm->addEventListener(array(Events::onClear), $this);
The effects of this bug are best visible when creating multiple iterator objects after each other in a repository:
// Loop through test code 10 times
for ($f = 0; $f < 10; $f<ins></ins>) {
// Create test query
$query = $this->createQueryBuilder('p')->getQuery();
// Create IterableResult object
$iterableResult = $query->iterate();
// Loop through the iterator
foreach ($iterableResult as $row) {}
// Print out memory usage
print(memory*get_usage() . PHP*EOL);
}
This results in the following output:
10536552
10549920
10563288
10576664
10590040
10603416
10616792
10630168
10643608
10656984
Notice how the used memory increases by about 13KB after each iteration.
To stop this memory leak the following code can be added to the end of the cleanup() function in the AbstractHydrator class:
$evm = $this->_em->getEventManager();
$evm->removeEventListener(array(Events::onClear), $this);
The output is now:
10537920
10537048
10537048
10537048
10537048
10537048
10537048
10537048
10537048
10537048
The reference to the event manager is now automatically removed in the cleanup function which allows the hydrator object to be cleaned up by the garbage collection function in PHP.