Search code examples
javaperformancejava-6java-5stringbuffer

Reusing StringBuffer


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 ?


Solution

    1. Use StringBuilder, a non-synchronized variant of StringBuffer -- that gives you a performance boost straight out of the box.
    2. No need to call trimToSize -- you are just forcing the StringBuilder to make a new char array.
    3. You'll save very, very little by reusing a StringBuilder since the JVM is highly optimized for the allocation of short-lived objects.
    4. Use StringBuilder instead 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 the StringBuilder.