Skip to content

Instantly share code, notes, and snippets.

@kdabir
Created July 22, 2011 03:22
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kdabir/1098824 to your computer and use it in GitHub Desktop.
compare the time taken while iterating over collection with closure and for loop
def file = "input.txt"
// just to heat up the jvm :)
new File(file).eachLine{
it.toUpperCase()
}
// with closure
start = System.nanoTime()
new File(file).eachLine{
it.toUpperCase()
}
println System.nanoTime() - start
// with loop
start = System.nanoTime()
lines = new File(file).readLines()
for (line in lines){
line.toUpperCase()
}
println System.nanoTime() - start
// read lines into a list
lines = new File(file).readLines()
// with list.each {}
start = System.nanoTime()
lines.each { line->
line.toUpperCase()
}
println System.nanoTime() - start
// with loop over list
start = System.nanoTime()
for (line in lines){
line.toUpperCase()
}
println System.nanoTime() - start
//// output with groovy-1.8.0 and jdk-1.6
// 4792229
// 11169576
// 2638604
// 465702
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment