Better than string concatenation?
If you ask
stringBufferVariable.append("something") .append("more"); ...
will work better than concatenation with + , then yes, usually. That all of these classes exist. Creating an object is expensive compared to updating the values in a char array.
It seems that if not all compilers now convert string concatenation to using StringBuilder in simple cases, such as str = "something" + "more" + "..."; . The only performance difference I can see is that the compiler will not have the advantage of setting the initial size. Tests will tell you if the difference is enough. Using + will do for more readable code.
From what I read, the compiler apparently cannot optimize the concatenation performed in the loop when it is something like
String str = ""; for (int i = 0; i < 10000; i++) { str = str + i + ","; }
so in these cases, you still want to explicitly use StringBuilder.
StringBuilder vs StringBuffer
StringBuilder not thread safe, and StringBuffer is a StringBuffer , but otherwise they do not match. The synchronization performed by StringBuffer makes it slower, so StringBuilder is faster and should be used if you do not need synchronization.
Should I use setLength ?
What your example looks like now. I don't think the setLength call gets anything as you create a new StringBuffer for each pass through the loop. What you really have to do is
StringBuilder sb = new StringBuilder(128); while (<some condition>) { sb.append(<something>) .append(<more>) ... ;
This avoids unnecessary object creation, and setLength will update the int variable in this case.
source share