title: Doctrine flush changes and free up memory
body: <p>I'm experiencing problems working on a Symfony project with low memory limit. I need to create several entities, add them to another entity (entities are associated) and then flush changes to database. This happens in a <code>while</code> loop. </p>
  
  <p>The problem is that sometimes the loop can't finish the whole cycle because the process crashes for memory exhausting. Of course I can't raise the memory limit.</p>
  
  <p>I try to explain you better with some code...</p>
  
  <h2>Entities structure</h2>
  
  <pre><code>class Device
  {
      /**
       * @ORM\ManyToMany(targetEntity="Resource", inversedBy="devices",cascade={"persist", "refresh"}, fetch="EXTRA_LAZY")
       */
      protected $resources;
  
      public function addResource(Resource $resource)
      {
          if ($this-&gt;resources-&gt;contains($resource)) return;
          $this-&gt;resources-&gt;add($resource);
          $resource-&gt;addDevice($this);
      }
  }
  
  class Resource
  {
      /**
       * @ORM\ManyToMany(targetEntity="Device", mappedBy="resources")
       */
      protected $devices;
  
      public function addDevice(Device $device)
      {
          if ($this-&gt;devices-&gt;contains($device)) return;
          $this-&gt;devices-&gt;add($device);
          $device-&gt;addResource($this);
      }
  }
  </code></pre>
  
  <h2>The loop</h2>
  
  <pre><code>function doIt(Device $device) {
      while(...) {
          $res = new Resource(...);
          $device-&gt;addResource($res); // store $res in memory until end
      }
      $em-&gt;persist($device);
      $em-&gt;flush();
  }
  </code></pre>
  
  <p>So the problem is that until the loop finishes, <code>$device</code> keeps in memory <code>Resource</code> objects and sometimes memory limit is reached.</p>
  
  <h2>What I tried so far</h2>
  
  <pre><code>function doIt(Device $device) {
     $i = 0;
     while(...) {
         $res = new Resource(...);
         $device-&gt;addResource($res);
         $i++;
         if ($i % 100 == 0) {
                $em-&gt;persist($device);
                $em-&gt;flush($device);
                $device-&gt;setResources(null); // free up Resources in memory
                $em-&gt;refresh($device); // Resources are not stored in memory
         }
     }
     $em-&gt;persist($device);
     $em-&gt;flush();
  }
  </code></pre>
  
  <p>This works not that good even because I see memory raising anyway (probably caused then by Doctrine). Moreover there are a lot of entities and several associations between them, and checking results in database gives me something wrong (e.g. an Entity not persisted).</p>
  
  <p>What would you do?</p>