Kotlin

Kotlin

Made by DeepSource

Array constructors should be preferred over the spread operator KT-P1004

Performance
Major

In most cases using a spread operator causes a full copy of the array to be created before calling a method. This has a very high performance penalty. The Kotlin compiler since v1.1.60 has an optimization that skips the array copy when an array constructor function is used to create the arguments that are passed to the vararg parameter. However, it is generally advisable to avoid using the spread operator.

Bad Practice

val strs = arrayOf("value one", "value two")
val foo = bar(*strs)

fun bar(vararg strs: String) {
    strs.forEach { println(it) }
}

Recommended

Prefer using array constructors over the spread operator.

// array copy skipped in this case since Kotlin 1.1.60
val foo = bar(*arrayOf("value one", "value two"))

// array not passed so no array copy is required
val foo2 = bar("value one", "value two")

fun bar(vararg strs: String) {
    strs.forEach { println(it) }
}