Is there any difference between using map and using function if everything is known at compile time? Maximal number of items will never be higher than 200, and most of the time it would be below 10.
Example:
val mappings = mapOf(
"PL" to "Poland",
"EN" to "England",
"DE" to "Germany",
"US" to "United States of America",
)
fun mappingsFunc(code: String): String? {
return when (code) {
"PL" -> "Poland"
"EN" -> "England"
"DE" -> "Germany"
"US" -> "United States of America"
else -> null
}
}
fun main() {
println(mappings["PL"]!!)
println(mappingsFunc("US")!!)
}
Practically, there is no difference, especially since you are using immutable
Maps (as opposed toMutableMap). I used Amazon'scorretto-18to compile your code and inspected the bytecode. Those are the conclusions I got from doing so:println(mappings["PL"]!!)compiles to the following bytecode:So it:
mappingsobject..get()on it.null.System.outobject..println()on it by passing theStringgotten from the map.In case of
println(mappingsFunc("US")!!), we have:which differs only in the first two operations. Instead of accessing any object and calling its method, it simply invokes the
mappingsFunc()method. Let us inspect what it does exactly:Lots of code, so let us inspect the only relevant part that we should pay attention to:
Before analyzing it further, it's worth to note that branches
L3,L4andL5are basically identical toL2- they just differ in a given String literal.The above bytecode invokes
String::hashCode()and thenString::equalsto pick the correct branch.Which is... basically the same thing as what
Map::get()does.In conclusion, those constructs are almost equivalent, with a single exception that the memory consumption and initial creation of the
mappingobject takes some time and memory. A negligible amount, though.In terms of recommendation, it depends on the scope of the usage. If the functions is local and used in a very limited scope, I would probably stick with the
whenexpression. However, if those options are loaded from some external config (and potentially need some precomputation), you ough to use theMapapproach.