What's the use of a StringBuffer? Why shouldn't I just use a String?


StringBuffer can improve the performance of your application or applet. Java has often been criticized for its slow execution - but often it can be sped up through efficient algorithms and application design. If your code uses strings that change in size, then converting to StringBuffers can be of benefit.

Consider the following example, where mystring grows in size :

String mystring = "";

for (int i = 0; i<=1000; i++)
	mystring = mystring + 'Number ' + i + '\n';

System.out.print (mystring);

In every cycle of the loop, we are creating a brand new string object, and the Java Virtual Machine must allocate memory for each object. It must also deallocate the memory for previous mystring instances (through the garbage collector), or face a hefty memory penalty.

Now consider the next example :

StringBuffer mystringbuffer = new StringBuffer(5000);

for (int i = 0; i<=1000; i++)
	mystringbuffer.append ( 'Number ' + i + '\n');
System.out.print (mystringbuffer);

Rather than creating one thousand strings, we create a single object (mystringbuffer), which can expand in length. We can also set a recommended starting size (in this case, 5000 bytes), which means that the buffer doesn't have to be continually requesting memory when a new string is appended to it.

While StringBuffer's won't improve efficiency in every situation, if your application uses strings that grow in length, it may be of benefit. Code can also be clearer with StringBuffers, because the append method saves you from having to use long assignment statements. StringBuffer has plenty of advantages - so consider using it in your next Java application/applet.