Kavan
02/03/2020, 8:20 PMval 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 ?Sam
02/03/2020, 8:48 PMstr
isn’t the same object type between your two examples.
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:
val b = StringBuilder()
repeat(1000) {
b.append("Hello")
}
repeat(1000) {
b.deleteCharAt(b.length / 2)
}
val str = b.toString()
Kavan
02/04/2020, 9:12 AMDico
02/04/2020, 11:58 AMdeleteCharAt
probably doesn't have such great performance.Dico
02/04/2020, 11:59 AMDico
02/04/2020, 11:59 AM