Came across 5 Performance Tips for Server Side Groovy at Groovy Blogs recently.
Point #2: “Be mindful of anonymous closures.” got me thinking (and then hacking)…
If this sort of thing floats your boat, consider the following:
def start = System.currentTimeMillis()
def i = 0
(1..100000000).each { i ++ }
println "Each: ${System.currentTimeMillis() - start}"
start = System.currentTimeMillis()
i = 0
for (x in 1..100000000) { i ++ }
println "For: ${System.currentTimeMillis() - start}"
In Groovy 1.6.3, using GroovyConsole, I get:
Each: 10033 For: 2973
Clearly, making all those closures for each to work with has an effect.
Is it significant? YMMV, etc. Certainly, I am glad to know about this: it’s the sort of thing that can bog server-side code down. Will I avoid using each (and the other collection-oriented closures)? No way! I accept that this sort of thing is going to happen, Groovy is a dynamic language, after all. I will keep it in mind, however: Forewarned, is forearmed…
I can’t resist the urge to reiterate The Correct Way to approach optimization.
