>
> And remember that StringBuffer never shrinks again, so be careful
> of reusing
> StringBuffer objects.
>

Some notes on reusing StringBuffer, ie: invoking setLength(0) after a
toString() is called.

- In JDK 1.2 and 1.3 the default buffer size is 16 characters.
- In JDK 1.2 calling setLength(0) would re-allocate the underlying char[]
with the same size.  So if you built up the buffer to 512 bytes, then did
setLength(0) (after calling toString), a new 512 byte char[] would be
allocated.
- In JDK 1.3 calling setLength(0) forces a new char[] of 16 characters.

In general, create a new StringBuffer each time you need one.  Try to give
it a slightly bigger size than you need.  Its worth doing some math on to
try to figure out a size distribution of the strings you're creating.  That
is, where its worth optimizing at all.

With the default size of 16, it also makes a difference how they're appended
to.  If it appends little pieces at a time to make a big string, it could be
wasting LOTS of char[]'s as it keeps allocating new char[]'s at double the
prior size.

StringBuffer b = new StringBuffer (); // take default of 16 chars
for (int i = 0; i < 128; i++) {
  b.append ("1");
}

After the above hits roughly i = 15 the original char[16] is copied to a new
char[32] and ready for GC.  After roughly i=31, the char[32] is copied to a
char[64] and ready for GC, etc.  By the time its done it will have create
new char[16], new char[32], new char[64], and new char[128].  The final
char[128] will be used for b.toString() but the intermediate 3 char[]'s were
pure waste.

And of course I think everybody knows that using the default StringBuffer
with "+" concatenation is bad (where performance counts, that is):

for (int i = 0; i < 50; i++) {
  String msg = "NUMBER " + i + "\tMESSAGE: " + mainMessage + "..." + ...
  someMethod (msg);
}

The main reason is that you can't tell the compiler to make the StringBuffer
bigger than the default 16, so it suffers the above buffer re-allocation
problems.

---
Obviously these should only be considered where performance can make a
difference, it does make the code more difficult to maintain.  If the string
size requirements change it might do more harm than good (if you use new
StringBuffer (64) but the most ever used is now 10, say).

HTH,

-j



Reply via email to