Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Benchmark anonymous function creation in Scala

View benchmark_23737147.scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
/**
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
Something went wrong with that request. Please try again.