Created
May 19, 2014 16:33
-
-
Save ziggystar/490f693bc39d1396ef8d to your computer and use it in GitHub Desktop.
Benchmark anonymous function creation in Scala
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
/** | |
Benchmark for the question "For comprehension and number of function creation" on SO. (http://stackoverflow.com/q/23737147/108915) | |
Answer: http://stackoverflow.com/a/23742289/108915 | |
*/ | |
object M { | |
def useIt(): Unit = { | |
println(variantA()) | |
println(variantB()) | |
println(variantC()) | |
println(variantD()) | |
} | |
def time(f: () => Unit,n: Int): Unit = { | |
val now = System.nanoTime() | |
var i = 0 | |
while(i<n){ | |
f() | |
i+=1 | |
} | |
println((System.nanoTime() - now)*1e-9) | |
} | |
val matrix = IndexedSeq.tabulate(1000, 1000) { case (x, y) => x + y } | |
def main(args: Array[String]): Unit = { | |
println("A") | |
for(_ <- 1 to 5) time(() => variantA,500) | |
println("B") | |
for(_ <- 1 to 5) time(() => variantB,500) | |
println("C") | |
for(_ <- 1 to 5) time(() => variantC,500) | |
println("D") | |
for(_ <- 1 to 5) time(() => variantD,500) | |
println("verify results") | |
useIt() | |
} | |
def variantA(): Int = { | |
var r = 0 | |
for { | |
row <- matrix | |
elem <- row | |
}{ | |
r += elem | |
} | |
r | |
} | |
def variantB(): Int = { | |
var r = 0 | |
val f = (x:Int) => r += x | |
for { | |
row <- matrix | |
elem <- row | |
} f(elem) | |
r | |
} | |
def variantC(): Int = { | |
var r = 0 | |
var i1 = 0 | |
while(i1 < matrix.size){ | |
var i2 = 0 | |
val row = matrix(i1) | |
while(i2 < row.size){ | |
r += row(i2) | |
i2 += 1 | |
} | |
i1 += 1 | |
} | |
r | |
} | |
def variantD(): Int = matrix.foldLeft(0)(_ + _.sum) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment