4 ms·
+ operator does use StringBuilder. But it will use a StringBuilder for each string expression. Take the following piece of code: String foo = ""; for (int
by mustpax 17y ago
+ operator does use StringBuilder. But it will use a StringBuilder for each string expression. Take the following piece of code:
String foo = "";
for (int i = 0; i < 1000; i++) {
foo += "x";
}
The inside of the for loop can be replaced with:
StringBuilder tmp = new StringBuilder(foo.length());
tmp.append("x");
foo = tmp.toString()
As you will notice, we are still copying over the string foo each time we concatenate. So building strings with + inside a loop will still give you the feared copy-string-each-time behavior. The new String.concat() trick is only useful for crafting long strings in a single go, i.e. in a single expression.
- jkb112 17y agoThe author has updated the post, string concat takes significantly more compared to the buffer or builder