I’m aware of the difference between concat, StringBuffer and StringBuilder. I’m aware of the memory issue with the StringBuffer.toString backing array which can explode memory. I’m even aware of the JDK Sun optimization consisting in allocation a power of two for initial capacity.
But I’m still wondering about the best way to reuse a StringBuffer (used in toString()) or, if reusing the StringBuffer is pertinent. Which one is better with memory and speed performance in mind ?
public String toString2() {
StringBuffer sb = new StringBuffer(<size>)
... several .append(stuff) ...
sb.trimToSize()
return sb.toString()
}
or
private StringBuffer sb = new StringBuffer(<size>)
public String toString2() {
sb.delete()
sb.setLength(1024)
sb.trimToSize()
... several .append(stuff) ...
return sb.toString()
}
And why ?
StringBuilder, a non-synchronized variant ofStringBuffer— that gives you a performance boost straight out of the box.trimToSize— you are just forcing theStringBuilderto make a new char array.StringBuildersince the JVM is highly optimized for the allocation of short-lived objects.StringBuilderinstead of a simple concatenation expression only if you cannot express your string in a single expression — for example, you are iterating over some stuff. Concatenation compiles to basically the same code using theStringBuilder.