Skip to content

Instantly share code, notes, and snippets.

@jlao
Created October 18, 2010 03:27
Show Gist options
  • Save jlao/631655 to your computer and use it in GitHub Desktop.
Save jlao/631655 to your computer and use it in GitHub Desktop.
A simple performance test comparing the performance of java.util.HashMap, scala.collection.immutable.HashMap, scala.collection.mutable.HashMap.
import java.util.HashMap
object MapPerf {
def main(args: Array[String]) {
if ( args.length < 2 ) {
println("Usage: scala MapPerf <number of elements to insert> <num trials>")
return
}
val numElements = args(0).toInt
val numTrials = args(1).toInt
println("This is a performance test comparing java.util.HashMap,")
println("scala.collection.immutable.HashMap, and scala.collection.mutable.HashMap.")
println("The test inserts " + numElements + " elements into each map.")
println()
println()
println("Testing Scala Immutable HashMap")
tester(numTrials) { scalaImmutableHMap(numElements) }
println()
println("Testing Scala Mutable HashMap")
tester(numTrials) { scalaMutableHMap(numElements) }
println()
println("Testing Java HashMap")
tester(numTrials) { javaHMap(numElements) }
println()
}
private def tester(numTrials: Int) (f: =>Double) {
var sum = 0.0
for ( i <- 0 until numTrials ) {
val time = f
println(f)
sum += f
}
println("----------")
println("Mean: " + (sum/numTrials))
}
private def timer[A](f: =>Unit): Double = {
val start = System.currentTimeMillis()
f
(System.currentTimeMillis() - start)/1000.0
}
private def javaHMap(numElements: Int): Double = timer {
val javaHMap = new HashMap[Int, String]()
for ( i <- 0 until numElements ) {
javaHMap.put(i, "foo" + i)
}
}
private def scalaImmutableHMap(numElements: Int): Double = timer {
var scalaIHMap = scala.collection.immutable.HashMap.empty[Int, String]
for ( i <- 0 until numElements ) {
scalaIHMap += ((i, "foo" + i))
}
}
private def scalaMutableHMap(numElements: Int): Double = timer {
val scalaMHMap = scala.collection.mutable.HashMap.empty[Int, String]
for ( i <- 0 until numElements ) {
scalaMHMap += ((i, "foo" + i))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment