3 ms·
Maybe I've been away from Java for too long, but I understand why the + operator's implementation is so much slower than that of String.concat(). If concat() us
by m0th87 17y ago
Maybe I've been away from Java for too long, but I understand why the + operator's implementation is so much slower than that of String.concat(). If concat() uses a StringBuilder, why doesn't the + operator as well?
- brown9-2 17y agoRead the comments at the end of the article... the author did not effectively test the String.concat() option (since he forgot to assign the results of the call to .concat() back to itself).
- deleted 17y ago[deleted]
- 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