Java – use characters instead of strings for single character values in StringBuffer append
I am passing the PMD rule appendcharacterwithchar It says avoid in StringBuffer Append concatenates characters into strings
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? How different is the performance between the following two pieces of code?
String text = new StringBuffer().append("some string").append('c').toString(); String text = new StringBuffer().append("some string").append("c").toString();
Solution
Appending a character as a char will always be faster than appending it as a string
But are performance differences important? If you only do it once, it won't If it repeats its body a million times in a cycle, yes, this may be important
If you already have this character at compile time, just take it as a character If it's stored in a variable of type string, don't bother accessing it Use string Charat (0) or some other methods, just append string
Note:
Like StringBuilder class to StringBuffer StringBuilder is faster because its methods are out of sync (you don't need it in most cases)
Side note 2#
This does not compile:
String text = new StringBuffer().append("some string").append('c');
Append() returns StringBuffer for linking You need to call tostring():
String text = new StringBuffer().append("some string").append('c').toString();