Since the calculation counts the objects count whenever a new instance is created, you may reach the limit and get an error about too many instances. To avoid this problem, put "def" outside the loops or closures.

So instead of doing:

for (record in records) {
  def cost = ....
}

Use this approach:

def cost
for (record in records) {
  cost = ....
}