Skip to content

Instantly share code, notes, and snippets.

@sherifkandeel
Created May 10, 2019 14:26
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 sherifkandeel/17f77c45e3cd356a29523cd20c1d8e2f to your computer and use it in GitHub Desktop.
Save sherifkandeel/17f77c45e3cd356a29523cd20c1d8e2f to your computer and use it in GitHub Desktop.
Comparing different Scala Map performance
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