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 ?
toString()method of anything be a performance bottleneck? If it is, then chances are thatStringis probably not the ideal thing to use for whatever operation you plan to do with it.