Appending one character


The performance benchmark was done by appending a single character to a StringBuffer by using either append(char) or append(String). This was done many times, after which the time it took was measured using System.currentTimeMillis(). The code inside the while loop looked like this:

StringBuffer sentence = new StringBuffer("Sentence number ");

This and the other tests in this article were done on three versions of the Sun compiler and JVM. Although there were some differences in the performance between the versions, the order from fastest to slowest did not change by running the tests on another JVM. The time in the graphs is an average of the three JVMs. That said, the tests were significantly faster on newer JVMs. Upgrading from Java 1.4.2 to Java 7 can give you an performance improvement of 50%.

The results are shown in the graph. Indeed, append(char) is faster than append(String). The String version takes almost 20% longer than the fast character version.

It makes sense that the String version takes longer. The two methods are basically the same, except that the String version has to check the length of the String. However, now that the JDK is open source, we can check the implementation instead of guessing the cause.

public AbstractStringBuilder append(char c) {
    int newCount = count + 1;
    if (newCount > value.length)
    value[count++] = c;
    return this;

This code copies character c to the end of a character array (line 5). Before doing this, it checks whether this character array is big enough (line 3) and increases its size if necessary (line 4).

public AbstractStringBuilder append(String str) {
    if (str == null) str = "null";
    int len = str.length();
    if (len == 0) return this;
    int newCount = count + len;
    if (newCount > value.length)
    str.getChars(0, len, value, count);
    count = newCount;
    return this;

This code copies the character array from the String parameter to the character array in the StringBuffer (line 8). Like the previous method it also checks whether the array is large enough, but now using the length of the String (lines 3-7). Getting the length of the String is not really a costly operation, because String stores its length in a field. However, there are a few more checks in this version, which makes it a bit slower.

The String version of append() is approximately 20% slower than the char version. In absolute terms, StringBuffer.append(String) takes 0.38 µs. whereas StringBuffer.append(char) takes 0.32 µs. This is only a 0.06 µs improvement, which is really a little. You won't notice the speed up until you call it thousands of times and if that is the case, there are better ways to get a speedup.

So it really doesn't matter which version of append() you use. On the other hand, you get the speedup for free: all else being equal, you can as well use the char version.