title: Grails controller (simple) code consuming too much memory. How to optimise?
body: <p>I have a pretty simple domain classes and a controller that while runtime consumes over 400MB - need some advice on optimising it.</p>
  
  <p>Basically I have two domain classes A and B, which are in a two one-to-many ralations (actually class B represents a many-to-many relationship between class A instances,  - single object of A can be referenced by multiple B's objects as 'fromA' and single object of A can be referenced by multiple B's objects as 'toA' - like the GORM documentation and flights and airports examples - A is an airport and B is a flight). Class A is a very simple domain class.</p>
  
  <pre><code>class A {
      static hasMany = [fromAs:B, toAs:B]
      static mappedBy = [fromAs:"fromA", toAs:"toA"]
  
      int ...
      String ...
      // several simple fields
  }
  </code></pre>
  
  <p>Class B is also very simple, it is just referencing class A in 2 ways.</p>
  
  <pre><code>class B {
      A fromA
      A toA
  
      int ...
      String ...
      // several simple fields
  }
  </code></pre>
  
  <p>Now what the controller does is to fill all the possible "flights" information to the database. It also does some really minor calculations of int's as setting of those int's but to make the code clear I'm skipping it.</p>
  
  <pre><code>A.list().each{ tempFromA -&gt;
      A.list().each{ tempToA -&gt;
          def b = new B()
              b.setFromA(tempFromA)
              b.setToA(tempToA)
              b.save(flush:false)
      }
  }
  </code></pre>
  
  <p>That's all the code and it consumes over 400MB od RAM. I tried calling hiernateSession.flush() every 10 000 records inserted, but always after 120 000 up to 300 000 records get commited, the out of memory occures.</p>
  
  <p>There are 610 A's in the database, so the embedded loops have over 370 000 cycles (610x610).</p>
  
  <p>Any guidelines how to optimise this code in terms of memory consuptions? It is so simple code that probably I'm doing something really stupid here...</p>