Java StringBuffer: append, Performance

These Java examples use the StringBuffer type to append many strings. A benchmark of StringBuilder and StringBuffer is done.
StringBuffer. Often we need to append many strings and form a larger, single string. With the String class this is slow. Many copies are done.
With StringBuffer, though, no copies are required after an append operation. The buffer within StringBuffer is mutable, changeable. We can convert it to a String with toString.
An example. We create a new instance of the String Buffer class and add ints and chars (spaces) to it. We append() in a loop. Often StringBuffer is used within loops.

Syntax: Please notice how we call the append method. We call append() on the result of another call.

Note: The append method returns an instance of the StringBuffer when it is done internally appending.

Java program that uses StringBuffer import java.lang.StringBuffer; public class Program { public static void main(String[] args) { // Create new StringBuffer. StringBuffer buffer = new StringBuffer(); // Append three ints and spaces. for (int i = 0; i < 3; i++) { buffer.append(i).append(' '); } System.out.println(buffer); } } Output 0 1 2
Performance. A StringBuffer is slower than a StringBuilder because it performs threading checks. In this benchmark I test this speed difference. I append 100,000 times to each class.

Times: The StringBuffer took over twice as much time. So the StringBuilder, in this situation, is a clear win.

Note: Other than the class name, the methods called here (append) are the same. They have equivalent effects.

Java program that benchmarks StringBuffer, StringBuilder import java.lang.StringBuilder; import java.lang.StringBuffer; public class Program { public static void main(String[] args) { long t1 = System.currentTimeMillis(); // ... Append to StringBuffer. StringBuffer buffer = new StringBuffer(); for (int i = 0; i < 100000; i++) { buffer.append(i).append(' '); } long t2 = System.currentTimeMillis(); // ... Append to StringBuilder. StringBuilder builder = new StringBuilder(); for (int i = 0; i < 100000; i++) { builder.append(i).append(' '); } long t3 = System.currentTimeMillis(); // ... Times. System.out.println(t2 - t1); System.out.println(t3 - t2); } } Output 14 ms, StringBuffer 6 ms, StringBuilder
Concepts. The newer type, StringBuilder, is preferable for speed. It performs over twice as fast in the benchmark. When no threads are involved, this is an easy speedup.
For the rare case when thread safety is needed when appending, StringBuffer is still useful. It works in nearly the same way as StringBuilder for appends and other operations.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls