Given I have a CharArray
. I want to convert to a String
.
Could someone tell me which of the following methods is better and why?
-
CharArray.concatToString()
-
CharArray.joinToString("")
Given I have a CharArray
. I want to convert to a String
.
Could someone tell me which of the following methods is better and why?
CharArray.concatToString()
CharArray.joinToString("")
concatToString()
is better because it is specialized for the case of concatenating characters from an array to a string, for example, it knows in advance of which size it should allocate a string builder.
Thanks for the explanation!
I have one extra question:
// create new string from "cab" to "abc"
val sortedStr = str.toCharArray().apply { sort() }.concatToString()
The code above needs 2 steps: “string to array” then “array to string”. Is there any way to make it perform better?
Remember strings in Java/Kotlin are immutable and that means almost every string processing requires first creating them as char arrays and then copying into string. Even if you do str1 + str2
then it creates a char array, copies str1
into it, then str2
, and then copies the resulting char array into the resulting string. Internally this is probably somehow optimized.
Also, as always, don’t do premature optimizations