is `StringBuilder` actually "efficient"? naively you're constructing a String by pushing a bunch of ...
y
is
StringBuilder
actually "efficient"? naively you're constructing a String by pushing a bunch of values which may reallocate partly through the operation, perhaps several times there's nothing special going on here, is there? in fact, I'd expect string formatting to be more amenable to optimization
not kotlin but kotlin colored 1
d
that is not a kotlin-related question. a quick google will answer it for you from multiple sources.
y
noted. I'll try to keep my questions Kotlin-specific in the future.
👍 1
s
I'm not sure I agree that this isn't Kotlin-related. It's true that on the JVM,
kotlin.text.StringBuilder
is currently implemented by calling straight through to
java.lang.StringBuilder
. But it's also part of the standard library on other platforms, including JS and Native. The fact that it sometimes uses a Java class under the hood is an implementation detail which isn't necessarily immediately obvious. I would say that "Kotlin behaves like Java in this respect" is actually just a good way to answer this question, not a reason to dismiss the question as off-topic.
4
k
I agree with Sam. In fact, in Kotlin/Native StringBuilder has a pure Kotlin implementation.
Interestingly, the native implementation doesn't appear to be as optimized as the JVM implementation. If you do
StringBuilder().append(someInt).append(anotherInt)
in Kotlin/Native, it does
StringBuilder().append(someInt.toString()).append(anotherInt.toString())
so you get intermediate object instances, whereas in the JVM implementation it renders the textual representations directly into the array owned by the StringBuilder.