Skip to content

Instantly share code, notes, and snippets.

@ericntd
Last active June 27, 2020 14:43
Show Gist options
  • Save ericntd/d632f9b805bf749c3ce63d7759ce988f to your computer and use it in GitHub Desktop.
Save ericntd/d632f9b805bf749c3ce63d7759ce988f to your computer and use it in GitHub Desktop.
fun compareMapInits(repeat: Int, size: Int) {
println(">>> compareMapInits for $size elements (repeated $repeat times)")
var totalMutableMapRuntime: Long = 0
var totalHashMapRuntime : Long = 0
var countHashMapSlower = 0
repeat(repeat) {
// mutableMapOf()
val startTime = System.currentTimeMillis()
val map = mutableMapOf<Int, Int>()
(0..size).forEach {
map[it] = it
}
val mutableMapRuntime = System.currentTimeMillis() - startTime
totalMutableMapRuntime += mutableMapRuntime
// HashMap()
val startTime2 = System.currentTimeMillis()
val map2 = HashMap<Int, Int>()
(0..size).forEach {
map2[it] = it
}
val hashMapRuntime = System.currentTimeMillis() - startTime2
totalHashMapRuntime += hashMapRuntime
if (hashMapRuntime > mutableMapRuntime) {
countHashMapSlower++
}
}
println("mutableMapOf() total time taken: $totalMutableMapRuntime ms")
println("HashMap() total time taken: $totalHashMapRuntime ms")
println("How often is HashMap() slower? ${countHashMapSlower}/$repeat")
println("<<<")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment