Fatal error: Allowed memory size of X bytes exhausted (tried to allocate Y bytes)...
I hate this message, in fact it says « You suck, you don’t even know what you’re doing with your objects ». It happened recently when I was writing a script which retrieves old data from an old database, computes it and inserts new values in an other database. I used Doctrine because it was a part of a Symfony project, and I discovered many things :
- Doctrine objects take a LOT of memory space
- PHP 5.2.11 does not garbage collects Doctrine (or any other ORM) objects at the end of the scope
Why? Because before PHP 5.3 the garbage collector can’t collect objects that have circular references, and that is the case of Doctrine objects. So they aren’t freed at the end of the scope, resulting in memory leakage.
So in order to process thousands/millions records with a database ORM, you need to handle memory freeing. Doctrine hopefully provides a
free() method which, combined with unset(), can solve your problem.
// ... $my_object = new MyDoctrineClass() ; // your data processing... $my_object->free() ; unset($my_object) ; // ...