3

I'm creating a query with an entity repository and it seems to have memory leaks.

In my Entity repository class:

echo 'mem 1 : ' . (memory_get_usage()/1024/1024) . "<br />\n";
$query = $this->createQueryBuilder('a')->select('a','b','c','...');
echo 'mem 2 : ' . (memory_get_usage()/1024/1024) . "<br />\n";
$r = $query->getQuery()->getResult();
echo 'mem 3 : ' . (memory_get_usage()/1024/1024) . "<br />\n";
$this->clear(true);
$query->getQuery()->free(true);
unset($r);
echo 'mem 4 : ' . (memory_get_usage()/1024/1024) . "<br />\n";

Output:

mem 1 : 5.0805282592773
mem 2 : 5.0998611450195
mem 3 : 91.49528503418
mem 4 : 77.939567565918

Why is the memory not back to the initial size (5 MB) after freeing the memory?

And only pass from 91 to 77.

user2342558
  • 5,567
  • 5
  • 33
  • 54
Seb33300
  • 7,464
  • 2
  • 40
  • 57

1 Answers1

5

Doctrine caches certain aspects of Entities it has loaded. Use

$em->clear(); 

to detach all objects from the current entity manager.

james_t
  • 2,723
  • 1
  • 15
  • 20
  • With this, the memory is down to 66 mb (mem 4). – Seb33300 Mar 07 '13 at 09:31
  • 3
    The additional memory is the result of the $r variable. unset() does not guarantee immediate garbage collection, so the process will retain that memory until the garbage collector has freed it or the process has terminated. See http://stackoverflow.com/questions/584960/whats-better-at-freeing-memory-with-php-unset-or-var-null for more detail. – james_t Mar 07 '13 at 14:41