4

It's recommended (PMD rule AppendCharacterWithChar) to use StringBuilder.append(char) instead of StringBuilder.append(String). I agree with that.

But if I want to append a (short) string like "='" or "</", is using

StringBuilder.append('=').append('\'')

better (faster) than

StringBuilder.append("='")

?

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Frank M.
  • 997
  • 1
  • 10
  • 19

1 Answers1

6

The code for the two methods is:

public synchronized StringBuffer append(char c) {
    toStringCache = null;
    super.append(c);
    return this;
}

public AbstractStringBuilder append(char c) {
    ensureCapacityInternal(count + 1);
    value[count++] = c;
    return this;
}

vs

public synchronized StringBuffer append(String str) {
    toStringCache = null;
    super.append(str);
    return this;
}

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

Some more work is done by the append(String) version, but it's trivial:

  • Some null checking;
  • Retrieving the length;
  • Copying a range of characters.

But this isn't really going to make much of a difference, at least for very short strings.

The more significant performance cost here is in the fact that StringBuffer methods are synchronized: in order to invoke either overload, a monitor has to be acquired on the StringBuffer. This takes some time - I would have thought longer than the extra work done. And calling append(char) means you have to acquire this monitor repeatedly.

The real performance hit here is for the squidgy bit between monitor and keyboard - you. Write code that is readable: the append(String) form is way easier to read than calling append(char) form over and over.

Also, use StringBuilder if you can - this avoids the synchronization issue entirely.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243