https://kotlinlang.org logo
#announcements
Title
# announcements
m

mathew murphy

07/24/2019, 6:10 PM
Is there any performance difference between
"${var1}${var2}"
and
var1 + var2
for string construction?
r

Ruckus

07/24/2019, 6:11 PM
The second only works for strings, whereas the first works with any value. (Also, you can just use
"$var1$var2"
)
m

mathew murphy

07/24/2019, 6:12 PM
Right, I was just wondering which I should prefer when my values are known to be non-null strings.
In Ruby the template substitution is faster than string append.
r

Ruckus

07/24/2019, 6:15 PM
Whichever you like more. Any difference will be negligible. My uneducated guess is they get compiled/optimized to roughly the same thing. Unless you are doing a metric fetch ton of those operations in a hot loop, I can't imagine the difference would contribute to your actual runtime.
c

Casey Brooks

07/24/2019, 6:15 PM
I believe the first is compiled to a
StringBuilder
under-the-hood. I’m not sure about the second, if it goes to a StringBuilder or does normal String concatenation. But it should either be the same performance-wise or slightly faster
m

mathew murphy

07/24/2019, 6:15 PM
Sounds like templates are probably the way to go then.
m

Marko Mitic

07/24/2019, 6:37 PM
I guess that best thing to do is to open kotlin bytecode, maybe decompile that to Java and see for yourself
r

Ruckus

07/24/2019, 6:41 PM
Don't decompile to Java. The decompiler has some magic code to try to reinterpret string concatenation into friendlier looking code. It's not representative of what it's actually doing. You'll have to read the bytecode directly.
💯 2
m

Mike

07/24/2019, 6:44 PM
I don't know when it was added. Javac will turn
+
operations into StringBuilder in 8+ at least. Not sure if it does it in 6 or 7. So could depend on which version of JDK, and could depend on whether Kotlin compiler is turning it into
+
, or turning it into StringBuilder?
c

Cody Engel

07/24/2019, 6:53 PM
in terms of which to prefer i would prefer string templates, it’s a feature of the language which makes life easier than having to do string concatenation in another way
💯 2
i can’t imagine the performance difference (if there are any) would be significant enough to do things the old way
s

SiebelsTim

07/24/2019, 9:36 PM
If I remember correctly, the resulting byte code is the same.
l

louis993546

07/29/2019, 5:55 PM
yup, it's the same (with
StringBuilder
)
👏 2
3 Views