Skip to content

Instantly share code, notes, and snippets.

@hrj
Created February 19, 2015 19:10
Show Gist options
  • Save hrj/c3e1b4dab12b944e12f7 to your computer and use it in GitHub Desktop.
Save hrj/c3e1b4dab12b944e12f7 to your computer and use it in GitHub Desktop.
Scala v/s Kotlin
var count = 0
var totalTime = 0L
fun test() {
val start = System.currentTimeMillis()
val x = (1L..5000000L) map {it * 40} reduce {a,b -> (a*b)%19 + 1}
val end = System.currentTimeMillis()
val timeTaken = (end - start)
totalTime += timeTaken
println("answer is: " + x)
println(" time: " + timeTaken + " ms")
count += 1
}
test()
test()
test()
test()
test()
test()
test()
test()
test()
test()
println("Avg time: " + (totalTime.toDouble() / count))
var count = 0
var totalTime = 0L
def test() {
val start = System.currentTimeMillis()
val x = (1L to 5000000L) map {_ * 40} reduce {(a,b) => (a*b)%19 + 1}
val end = System.currentTimeMillis()
val timeTaken = (end - start)
totalTime += timeTaken
println("answer is: " + x)
println(" time: " + timeTaken + " ms")
count += 1
}
test()
test()
test()
test()
test()
test()
test()
test()
test()
test()
println("Avg time: " + (totalTime.toDouble / count))
@hrj
Copy link
Author

hrj commented Feb 19, 2015

Benchmark results

Kotlin

$ kotlinc -version
INFO: Kotlin Compiler version 0.10.195

$kotlinc -script test.kts
Avg time: 3763.3333333333335 ms

Scala

$ scala -version
Scala code runner version 2.11.5 -- Copyright 2002-2013, LAMP/EPFL

$ scala test.scala
Avg time: 478.5 ms

@openaphid
Copy link

I got different result from yours. Kotlin version is much faster than Scala.

Java 1.8.0_31 Mac 10.9.5
Kotlin:
Avg time: 171.2

Scala 2.11.5
Avg time: 649.7857142857143

@talvik
Copy link

talvik commented Sep 18, 2015

JRE 1.8.0_60

    Scala Kotlin Java
Version 2.11.7 0.13.1513 1.8.0
Avg time 393ms 530ms 35ms
Avg after warmup 200ms 220ms 30ms

Java version:

long x = LongStream.rangeClosed(1l, 5000000l)
        .map(n -> n * 40)
        .reduce((a, b) ->  (a * b) % 19 + 1)
        .getAsLong();

@ctongfei
Copy link

In Scala you should do (1 to 1000000).view that turns it lazy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment