I was going through the PMD rule AppendCharacterWithChar
. It says Avoid concatenating characters as strings in StringBuffer.append.
StringBuffer sb = new StringBuffer();
// Avoid this
sb.append("a");
// use instead something like this
StringBuffer sb = new StringBuffer();
sb.append('a');
Do I really need this PMD rule? Is there much performance difference between the following two piece of code?
String text = new StringBuffer().append("some string").append('c').toString();
String text = new StringBuffer().append("some string").append("c").toString();
Appending a character as a char
will always be faster than appending it as a String
.
But does the performance difference matter? If you just do it once, it doesn't. If it is inside a cycle repeating its body a million times, then yes, it might matter.
If you already have the character at compile time, just append it as a character. If it is stored in a variable with String
type, don't bother accessing it e.g. with String.charAt(0)
or some other ways, simply just append the String
.
On a Side Note:
Favor the StringBuilder
class to StringBuffer
. StringBuilder
is faster because its methods are not synchronized (which you don't need in most cases).
On a Side Note #2:
This won't compile:
String text = new StringBuffer().append("some string").append('c');
append()
returns StringBuffer
for chaining. You need to call toString()
on it:
String text = new StringBuffer().append("some string").append('c').toString();