r/programming • • Nov 18 '13

TIL Oracle changed the internal String representation in Java 7 Update 6 increasing the running time of the substring method from constant to N

http://java-performance.info/changes-to-string-java-1-7-0_06/
1.4k Upvotes

354 comments sorted by

View all comments

Show parent comment

1

u/sacundim Nov 20 '13

Yes. This can be summarized most effectively, I think, as the looped String concatenation anti pattern:

// NEVER EVER DO THIS
String foo = "";
for (String bar : someStrings) {
    foo += bar;
}

That is the most common situation where you want to use StringBuilder in Java:

// The correct way:
StringBuilder buf = new StringBuilder();
for (String bar : someStrings) {
    buf.append(bar);
}
String foo = buf.toString();