Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: Is for..in significantly faster than .each?

I'm curious if for..in should be preferred to .each for performance reasons.

like image 818
Alexander Suraphel Avatar asked Jun 05 '15 08:06

Alexander Suraphel


1 Answers

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:

  • 3327981 each {}
  • 320949 for(){

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:

  • 261062715 each{}
  • 64518703 for(){}
like image 74
frhack Avatar answered Sep 21 '22 21:09

frhack