Last active
June 27, 2020 14:43
-
-
Save ericntd/d632f9b805bf749c3ce63d7759ce988f to your computer and use it in GitHub Desktop.
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
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