Skip to content

Instantly share code, notes, and snippets.

@XuefengWu
Created January 21, 2015 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XuefengWu/5af4421e4ec12925c54a to your computer and use it in GitHub Desktop.
Save XuefengWu/5af4421e4ec12925c54a to your computer and use it in GitHub Desktop.
test code for scala foreach performance test
object ScalaForApp extends App {
val scalaFor = new ScalaFor()
benchmark("testForeach", 10){scalaFor.testForeach()}
benchmark("testWhile", 10){scalaFor.testWhile()}
def benchmark(msg: String, times: Int)(f: => Unit): Unit = {
var i = 0
val start = System.nanoTime()
while(i != times){
f
i+=1
}
println(s"$msg spend: ${(System.nanoTime() - start)/times/1000}")
}
}
class ScalaFor {
val total: Int = 1000*1000*1000
def testForeach(): Unit ={
var count = 0
foreach(_ => count += 1)
}
def testWhile(): Unit ={
var i = 0
while(i != total){
i+=1
}
}
def foreach(f: Int => Unit): Unit ={
var i = 0
while(i != total){
f(i)
i+=1
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment