`val str = StringBuilder (); str.append("hello");`...
# kotlin-native
k
val str = StringBuilder (); str.append("hello");
var str = ""; str += "hello";
Second is faster then first one. Shouldn't take same time ? If not then. When to use first and when to use second ?
s
str
isn’t the same object type between your two examples.
Copy code
val b = StringBuilder()
b.append("hello")
val str = b.toString()
Allocations are relatively cheap so for minor amounts of string concatenation, the code is often clearer with just
str += "hello"
but if you’re going to be doing heavy manipulation of the string before it is fully constructed a
StringBuilder
should perform better. Try a heavier example like this and see how it performs:
Copy code
val b = StringBuilder()
repeat(1000) {
    b.append("Hello")
}
repeat(1000) {
    b.deleteCharAt(b.length / 2)
}
val str = b.toString()
👍 3
k
Got it. Thanks.
d
deleteCharAt
probably doesn't have such great performance.
Probably better than concatenating 2 sub strings though
So good example