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("='") 

?

2
  • 2
    You'd get a more substantial performance boost by switching to StringBuilder. Commented Mar 10, 2017 at 14:47
  • 1
    This won't make any noticeable difference. Switch to StringBuilder, and use the version that is the most readable. Commented Mar 10, 2017 at 15:02

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.