Menu

#513 Promote StringBuilder over StringBuffer

open
nobody
rules (229)
5
2014-02-08
2008-10-20
No

For Java 1.5+, the use of StringBuilder should be used over StringBuffer because StringBuilders are not synchronized. StringBuilders are designed to be drop-in replacement for StringBuffer, so it is a pretty easy migration. The only case that I wouldn't recommend this transformation is if the StringBuffer is leaving local scope -- but from my experience, that is rare...

Consider the following code:

public String toString () {
final StringBuffer sb = new StringBuffer();
sb.append("MyClass[a=");
sb.append(a);
sb.append(",b=");
sb.append(b);
sb.append(']
');
return sb.toString()
}

This should be:

public String toString () {
final StringBuilder sb = new StringBuilder();
sb.append("MyClass[a=");
sb.append(a);
sb.append(",b=");
sb.append(b);
sb.append(']
');
return sb.toString()
}

However, imagine the following case:

final StringBuffer sb = new StringBuffer();
sb.append("Some text here.");
foo(sb);
return sb.toString();

This can not be changed from StringBuffer to StringBuilder because:
1. The foo signature likely requires StringBuffer (it could be Object, I guess...)
2. The foo method may mutate the StringBuffer, and that mutation may require synchronization.

From my experience, over 90% of code with StringBuffer falls into the above case where it is simply a local variable that could be easily transitioned. (I was skeptical at the performance difference, particularly with Java 6, but then an article highlighted how expensive it still is: http://www.infoq.com/articles/java-threading-optimizations-p1).

Discussion


Log in to post a comment.