Java can concatenate Strings using the + operator.  Where there are only few parts to join together it is better to use the + operator to add the Strings together.  StringBuilder construction takes time and the additional code bloat is not worth the processor savings of a few nanoseconds.

For example:

StringBuilder buf = new StringBuilder();
buf.append(' ');
String fullName = buf.toString();

Since only a few values together are needed to create a fullName, it would be better written as:

String fullName = firstName + ' ' + familyName;

If there were more values to append you might consider using a StringBuilder instead but the following exception applies:

Any code that does not directly impact performance (such as for reporting error messages) does not need to use StringBuilder at all.  Appending Strings using a buffer is only required in library or looping code that will be called many times and affect performance.  Code used to render popular web pages can cause performance problems too if a thousand users hit the page at once so StringBuilders may be appropriate in Controllers.

blog comments powered by Disqus