StringBuffers are often underused by novice
Java programmers. It isn't obvious why it's better to use a StringBuffer than just a
String. But believe me, there is a big difference.
The difference is when you
concatenate strings. If you
append a String onto a StringBuffer, the StringBuffer takes the String, copies the String's
characters onto itself, and that's it. Pretty simple, right?
But when you concatenate Strings, here's basically what happens:
- One String creates a new StringBuffer, which it initializes with itself.
- This StringBuffer appends the 2nd String onto itself.
- The StringBuffer calls toString() on itself and returns the new String, which is then returned from the String concatenation.
This way has much more overhead in terms of both
memory and
cpu time. Generally, if you are going to need to concatenate to a string more than a couple of times, you will get noticeably better
performance from a StringBuffer.
<
anecdote border="0" lame="1">
A while ago, I wrote an
application which wrote an
order (from an online catalog) to a file. The
file contained the
customer info, order notes, each
product ordered including
quantity and
price, etc. Well, I didn't appreciate the value of a StringBuffer at the time, so I just used a String and concatenated the data together. It worked fine in my
tests, because I only did small orders. But later we discovered that it wouldn't work with large orders - the server would
time out. After we changed it to StringBuffer, we haven't been able to find an
upper limit to the size of the order.
</anecdote>