compare the time taken while iterating over collection with closure and for loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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