Hidden allocations when using vararg and spread operator

You can check with Tools > Kotlin > Show Kotlin Bytecode

Here’s my sample code:

fun doStuff(vararg data : String) {

}

fun main(args: Array<String>) {
    val arr = arrayOf("a", "b", "c")
    doStuff(*arr)
}

Here is what is created for the call to doStuff

    LINENUMBER 9 L6
    ALOAD 1
    DUP
    ARRAYLENGTH
    INVOKESTATIC java/util/Arrays.copyOf ([Ljava/lang/Object;I)[Ljava/lang/Object;
    CHECKCAST [Ljava/lang/String;
    INVOKESTATIC tfo/sample/ArraySpreadKt.doStuff ([Ljava/lang/String;)V
   L7

The Oracle Java compiler does not copy the array but passes it directly to the method:

  LINENUMBER 11 L1
    ALOAD 1
    INVOKESTATIC tfo/sample/JavaArraySpread.doStuff ([Ljava/lang/String;)V

Kotlin is using the safe approach here (copying the array) whereas Java saves the object allocation and copy.

4 Likes