I'm curious if for..in
should be preferred to .each
for performance reasons.
For .. in
is part of the standard language flow control.
Instead each
calls a closure so with extra overhead.
.each {...}
is syntax sugar equivalent to the method call .each({...})
Moreover, due to the fact that it is a closure, inside each
code block you can't use break
and continue
statements to control the loop.
http://kunaldabir.blogspot.it/2011/07/groovy-performance-iterating-with.html
Updated benchmark Java 1.8.0_45 Groovy 2.4.3:
Here is another benchmark with 100000 iterations:
lines = (1..100000)
// with list.each {}
start = System.nanoTime()
lines.each { line->
line++;
}
println System.nanoTime() - start
// with loop over list
start = System.nanoTime()
for (line in lines){
line++;
}
println System.nanoTime() - start
results:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With