Sam Stone
11/23/2022, 5:55 AMif(string !in arrayOf("str1", "str2", "str3"...)) foo()
Option 2:
if(string != "str1" && string != "str2" ...) foo()
Option 3:
when(string) { "str1", "str2", "str3" -> {} else -> foo())
The bytecode for option 3 uses `string`’s hashcode in something like:
label20: {
switch(string.hashCode()) {
case 3541024:
if (string.equals("str1")) {
break label20;
}
break;
case 3541025:
if (string.equals("str2")) {
break label20;
}
break;
case 3541026:
if (string.equals("str3")) {
break label20;
}
}
foo()
}
ephemient
11/23/2022, 6:33 AMSam Stone
11/23/2022, 6:44 AMSam Stone
11/23/2022, 6:45 AMRohde Fischer
11/23/2022, 7:17 AMO(n^n)
algorithms either, don't take the premature optimization point to its absurd extreme)Klitos Kyriacou
11/23/2022, 8:55 AM&&
operator and it's perfectly clear. For 3 or more strings, I find option 1 more readable. But if you have more than one such if
check in a function, and one of them has 2 strings and the other 3 strings, I would make both of them use option 2 for consistency.phldavies
11/23/2022, 9:22 AMwhen(string) {
"str1", "str2" -> //...
}
is also a viable option - the downside being needing two nested blocksRoukanken
11/23/2022, 9:23 AMephemient
11/23/2022, 9:24 AMarrayOf
- throughout all Kotlin code, using it instead of listOf
is an intentional decision. it is understandable in this usage but as a reader of the code it takes me longer to check than otherwiseephemient
11/23/2022, 9:26 AMif (string in ["str1", "str2"...])
similar to the feature request for https://youtrack.jetbrains.com/issue/KT-36184ephemient
11/23/2022, 9:27 AMmcpiroman
11/23/2022, 11:28 AMKlitos Kyriacou
11/23/2022, 3:57 PMif (str in setOf("a", "b"))
in a performance-critical loop, then be aware that setOf
can be inefficient:
1. It creates a new array in every loop
2. For each element of the array, it adds it to a LinkedHashSet (and thus spends time calculating a hash and creating next and previous links)
On the other hand, arrayOf
just creates a new array.Sam
11/23/2022, 3:58 PMif (string in "str1str2str3")
🧌Sam Stone
11/23/2022, 6:56 PMSam Stone
11/23/2022, 6:58 PM