Is there any performance difference between `"${va...
# announcements
m
Is there any performance difference between
"${var1}${var2}"
and
var1 + var2
for string construction?
r
The second only works for strings, whereas the first works with any value. (Also, you can just use
"$var1$var2"
)
m
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
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
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
Sounds like templates are probably the way to go then.
m
I guess that best thing to do is to open kotlin bytecode, maybe decompile that to Java and see for yourself
r
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
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
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
If I remember correctly, the resulting byte code is the same.
l
yup, it's the same (with
StringBuilder
)
👏 2