Created
May 10, 2019 14:26
-
-
Save sherifkandeel/17f77c45e3cd356a29523cd20c1d8e2f to your computer and use it in GitHub Desktop.
Comparing different Scala Map performance
This file contains 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 scala.collection.concurrent | |
import scala.collection.immutable._ | |
val concurrentTrieMap: concurrent.Map[String, String] = concurrent.TrieMap.empty | |
var immutableMap: Map[String, String] = Map.empty | |
var hashMap: HashMap[String, String] = HashMap.empty | |
def time[R](block: => R): String = { | |
val t0 = System.nanoTime() | |
block | |
val t1 = System.nanoTime() | |
(t1 - t0) + "ns" | |
} | |
val r = new scala.util.Random(31) | |
val keys = 1 to 100 map (_ => r.alphanumeric.take(3).mkString) | |
val values = 1 to 100 map (_ => r.alphanumeric.take(100).mkString) | |
println("populating time: ") | |
print("concurrentTrieMap ", | |
time { | |
keys.foreach { key => | |
values.foreach { value => | |
concurrentTrieMap.put(key, value) | |
} | |
} | |
}) | |
print("immutableMap ", | |
time { | |
immutableMap = (for { | |
key <- keys | |
value <- values | |
} yield key -> value) (collection.breakOut) | |
}) | |
print("hashMap ", | |
time { | |
hashMap = (for { | |
key <- keys | |
value <- values | |
} yield key -> value) (collection.breakOut) | |
}) | |
// lookup | |
println("Lookup time ") | |
val runs = 1 to 1000000 | |
val keySequence = runs map (_ => keys(r.nextInt(100))) | |
print("concurrentTrieMap ", | |
time { | |
keySequence foreach { oneKey => | |
concurrentTrieMap.get(oneKey) | |
} | |
}) | |
print("immutableMap ", | |
time { | |
keySequence foreach { oneKey => | |
immutableMap.get(oneKey) | |
} | |
} | |
) | |
print("hashMap ", | |
time { | |
keySequence foreach { oneKey => | |
hashMap.get(oneKey) | |
} | |
} | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment