This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
[ April 21, 2008: Message edited by: Nitesh Kant ]
If this was my problem I would simply create the StringBuffer (or StringBuilder) with an initial size well in excess of the needed capacity. If you use the default size, StringBuffer will be automatically expanding in small jumps, creating many many extra objects and consuming lots of time.
Well, 2 MB doesn't sound all that big to me. But if you're appending to a file, why do you need a StringBuffer (or StringBuilder) at all? You can just use a BufferedWriter wrapped in a FileWriter, in append mode. Just write the data directly to the file. Well, using a BufferedWriter means it's not quite direct, but that's a minor point. You'll store some of the data in memory for a while before writing it, but the buffer size can be much less than 2 MG if that's a problem.