https://kotlinlang.org logo
#getting-started
Title
# getting-started
u

ursus

05/13/2022, 11:05 PM
I have a api which takes varargs. Its basically a wrapper around String.format and there is a few layers to it. From what I see in the bytecode, every function call forces me to use spread operator which creates a copy of the vararg string array. Should I optimize this away and pass around only a Array<String>? feels very wasteful .. I mean we pass by reference on JVM // Not to mention if I call kotlin
format
then there is another damn copy when it proxies to java TLDR; are vararg apis harmful?
e

ephemient

05/13/2022, 11:37 PM
if you're calling a vararg Kotlin function, you can avoid the copy by using the named parameter instead of a spread if you're calling Java, https://youtrack.jetbrains.com/issue/KT-17043
u

ursus

05/14/2022, 12:13 AM
hmm I still see the copying
Copy code
fun initialize() {
    foo("meh", "yo")
}

fun foo(vararg args: String) {
    bar(args = args)
}

fun bar(vararg args: String) {
}
Copy code
public final void initialize() {
  this.foo("meh", "yo");
}

public final void foo(@NotNull String... args) {
  Intrinsics.checkNotNullParameter(args, "args");
  this.bar((String[])Arrays.copyOf(args, args.length)); <---------------
}

public final void bar(@NotNull String... args) {
  Intrinsics.checkNotNullParameter(args, "args");
}
e

ephemient

05/14/2022, 3:24 AM
that's surprising, and breaks my expectations; I've commented on the issue as such. I suppose there are no workarounds for the copy aside from reflection.
u

ursus

05/14/2022, 10:12 AM
oh well, varargs are stupid