I recently had to create 7.000 Grails domain objects in a loop and save them into the database.
It took a lot of time to save these 7k objects, so I analysed why it was slow.
As it turned out, using Groovy’s map constructor aka named parameters took a lot of time.
I created the objects this way:
MyDomain myDomain = new MyDomain(propA: element.a, propB: element.b)
The object creation took 30s. That is much too long for “just” 7.000 objects.
I switched to default constructor and set the properties via setters:
MyDomain myDomain = new MyDomain() myDomain.propA = element.a myDomain.propB = element.b
Now it took only one single second to create all the objects!
I don’t know why using named parameters to create Grails domain objects is that slow. At first I thought that the instantiation of the HashMaps and setting the arguments into the map for every constructor call is the problem. But that’s not the case: when testing this with plain groovy classes, it is fast (named parameters slow down object creation by factor 1.2 to 1.5). So it seams to have something to do with Grails domain classes.
My conclusion is that I will avoid named parameters when I have to create a lot of Grails domain objects.
When creating just a few domain objects, I will stick with Groovy’s map constructor because it will be much easier to read the code.
Maybe this is already fixed in newer Grails versions – I am using version 1.2.2.