I'm trying to understand what is the best way to navigate maps in kotlin (and swift), when you need to navigate the whole map. Both languages offer a .values method that make the navigation simpler, but with a C++ background I thought it could not perform in a decent way since it should create a vector of values with an additional navigation of the map (and a relevant memory allocation).
Basically my question is about this code:
val map: MutableMap<Int, String> = mutableMapOf()
for (i in 1.. 1000000) {
map[i] = "Value of this element is $i"
}
for (v in map.values)
if (v[0] != 'V')
Log.e(TAG, "ERROR!")
for ((_, v) in map) // it should be faster!
if (v[0] != 'V')
Log.e(TAG, "ERROR!")
... I've done a few benchmark of this code, timing the results with System.currentTimeMillis() and using one or two different maps, to avoid cache effects...
But I cannot get meaningful results... here is a complete program in kotlin native, that shows (differently from kotlin on JVM) a behaviour that is the contrary of the one I expected, I used two different maps and two tests per algorithm to exclude cache advantages.
import kotlin.system.*
fun main() {
val m1 : MutableMap<Int, String> = mutableMapOf()
val m2 : MutableMap<Int, String> = mutableMapOf()
println("Creating map...")
var st = getTimeMillis()
for (i in 1..2000000) {
m1[i] = "Test $i"
m2[i] = "Test $i"
}
var end = getTimeMillis()
println("Took: ${end - st} msecs, map size: ${m1.size},${m2.size} elements")
st = getTimeMillis()
for ((_, v) in m1)
if (v[0] != 'T')
println("ERROR!");
end = getTimeMillis()
println("Algorithm 1 (k,v): ${end - st} msecs")
st = getTimeMillis()
for (v in m2.values)
if (v[0] != 'T')
println("ERROR!");
end = getTimeMillis()
println("Algorithm 2 (values): ${end - st} msecs")
st = getTimeMillis()
for ((_, v) in m2)
if (v[0] != 'T')
println("ERROR!");
end = getTimeMillis()
println("Algorithm 1bis (k,v): ${end - st} msecs")
st = getTimeMillis()
for (v in m1.values)
if (v[0] != 'T')
println("ERROR!");
end = getTimeMillis()
println("Algorithm 2bis (values): ${end - st} msecs")
}