Let’s say we have some code that works with arrays (not lists, because of some platform APIs or third-party library):
fun compute() : Array<String> {
val firstArray = computeFirst()
val secondArray = computeSecond()
return firstArray + secondArray
}
In my cases both computeFirst
and computeSecond
may return empty array as a result.
Plus operator for arrays is defined in _ArraysJVM.kt
of stdlib as:
public actual operator fun <T> Array<T>.plus(elements: Array<out T>): Array<T> {
val thisSize = size
val arraySize = elements.size
val result = java.util.Arrays.copyOf(this, thisSize + arraySize)
System.arraycopy(elements, 0, result, thisSize, arraySize)
return result
}
On JVM an empty array is effectively immutable and can be reused in case of two empty arrays are concatenated with .plus()
. How is it implemented in Kotlin JS and Native worlds?
Is it possible to optimize Array.plus
operator considering empty arrays? E.g. if both operands are empty, return one of them as a result? It seems it is possible to optimize this at least for JVM in _ArraysJVM.kt
.
Example:
public actual operator fun <T> Array<T>.plus(elements: Array<out T>): Array<T> {
if (this.isEmpty() && elements.isEmpty()) return this
val thisSize = size
val arraySize = elements.size
val result = java.util.Arrays.copyOf(this, thisSize + arraySize)
System.arraycopy(elements, 0, result, thisSize, arraySize)
return result
}