Toady while listening to this video I discovered an interesting fact about usage of closure vs regular loop for iterating over list. So I wrote a quick test to confirm and yes loops outperform closures in terms of performance in case of iterating over a list.
But in a slightly similar case of
Here is the github gist, to get the latest version of code.
Results (with groovy-1.8.0 and jdk-1.6)
But in a slightly similar case of
File.eachLine{}
vs loading file in a list and then iterating with for
, the closure still works out faster on the whole. I have not tested this for different file sizes, but damn, whatever it may be new File(file).eachLine{}
just rocks :)Here is the github gist, to get the latest version of code.
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
Results (with groovy-1.8.0 and jdk-1.6)
Run # 1 Run # 2 Run # 3 Run # 4 4792229 4773791 4840280 5428064 11169576 10254934 10791595 12546008 2638604 2424610 2477969 2466514 465702 315403 315403 412063
No comments:
Post a Comment