Created
March 20, 2018 23:47
-
-
Save timotta/7ea799124f78bb7c2e31b9c356d8a885 to your computer and use it in GitHub Desktop.
Result:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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