Skip to content

Instantly share code, notes, and snippets.

@timotta
Created March 20, 2018 23:47
Show Gist options
  • Save timotta/81d7a2a4ae51c80db18f80c1615f2479 to your computer and use it in GitHub Desktop.
Save timotta/81d7a2a4ae51c80db18f80c1615f2479 to your computer and use it in GitHub Desktop.
Result:
import java.util.ArrayList
import java.util.HashMap
import scala.collection.JavaConverters.asScalaBufferConverter
import scala.collection.mutable.{Map => MapMutable}
object MapBenchmark {
def main(args: Array[String]): Unit = {
val hm = new HashMap[String, String]()
hm.put("teste1", "ok1")
hm.put("teste2", "ok2")
val mm = MapMutable[String, String]()
mm.put("teste1", "ok1")
mm.put("teste2", "ok2")
val series = 1000
val timesHashmap = new ArrayList[Long](series)
val timesMutable = new ArrayList[Long](series)
val times = 1000000
0.to(series).foreach { i =>
if (i % 100 == 0) println(i)
timesHashmap.add(timeit(() => many(times, (_) => hm.get("teste2"))))
timesMutable.add(timeit(() => many(times, (_) => mm.get("teste2"))))
}
println("hashmap mean=", mean(timesHashmap), "p50=", px(timesHashmap, 50), "p99=", px(timesHashmap, 99))
println("mutable mean=", mean(timesMutable), "p50=", px(timesMutable, 50), "p99=", px(timesMutable, 99))
}
def mean(m: ArrayList[Long]): Double = {
val n = m.asScala.toList
n.sum / n.size.toFloat
}
def px(m: ArrayList[Long], x: Int): Double = {
val n = m.asScala.toList
val p = (n.size / 100.0 * x).toInt
n.sortBy(a => a).apply(p)
}
def timeit(f: Function0[Unit]): Long = {
val before = System.currentTimeMillis()
f()
System.currentTimeMillis() - before
}
def many(times: Int, f: Function1[Int, Unit]): Unit = {
0.to(times).foreach(f)
}
def getHashMap(key: String, map: HashMap[String, String]): Unit = {
map.get(key)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment