avoid symfony2 leak of memory

From: https://coderwall.com/p/awzjhw


Migration script uses lot of Doctrine Queries. In case of lot data to migrate it can fail because of memory limit is reached.


PHP script is consuming memory after each query and data modification. This mean memory leaks if PHP process is long. When memory limit is reached script throw exception and migration process fails.


Here are some tips how to control memory usage when using Symfony2 and Doctrine EntityManager. You are able to keep memory consumption of reasonable level.
  • Remember to unset object if not needed
$obj = null;
Both does the same, but unset() does not force immediate memory freeing. PHP's garbage collector will do it when it see fits - by intention as soon, as those CPU cycles aren't needed anyway or as late as before the script would run out of memory, whatever occurs first. Using $obj = null; will rewrite variable's data. It might get memory freed faster, but it may steal CPU cycles from the code that truly needs them sooner, resulting in a longer overall execution time, but lower memory consumption.
  • Define no logging and profilling in config.yml
                    driver: ...
                    logging: false
                    profiling: false
  • Tune php.ini to use all available memory of server.
memory_limit = -1
It can be dangerous. Keep in mind to enable it only for migration process. After that set to some realiable value. It allows you to use large amount of memory if needed to prevent out of memory error.
  • If you are using PHP at least 5.3 you can force garbage collection after destroying object
*Remember to call gc_enable() first
  • Use EntityManager cleaning functions
  • Disable SQL Logger
Doctrine by default logs all queries. Turning it off will save extra memory consumption.