I was just wondering why the `1` element optimizat...
# stdlib
e
I was just wondering why the
1
element optimization in
toList
Copy code
public fun <T> Array<out T>.toList(): List<T> {
    return when (size) {
        0 -> emptyList()
        1 -> listOf(this[0])
        else -> this.toMutableList()
    }
}
Looking at the
listOf
implementations it's mostly redundant checks and basically spawning another
ArrayList
, same as
toMutableList
o
AFAIR there is listOf(arg) which creates specific list implementation for one element (at least on JVM)
👍 1
Copy code
public actual fun <T> listOf(element: T): List<T> = java.util.Collections.singletonList(element)
e
I get this for
commonMain
in multiplatform
Copy code
public fun <T> listOf(vararg elements: T): List<T> = if (elements.size > 0) elements.asList() else emptyList()
asList
again is then actualized with
ArraysUtilJVM.asList(this)
, which spawns an
ArrayList
So it's like multiple additional calls for the same result as
toMutableList
, at least in KMP
Ahh wait! Maybe the IDE navigation lands on the wrong function?
Looks like the vararg alternative is prioritized.