The use of a StringBuilder
or StringBuffer
makes String
assembly more efficient than plain concatenation
when you perform a large number of appends. Using String
concatenation within StringBuilder.append
defeats the purpose of
the StringBuilder
. If you concatenate only a few strings, use direct String
concatenation. Otherwise, replace
String
concatenation with calls to append
.
This rule applies to String concatenations performed repeatedly, inside loops. In such scenarios, the performance penalty associated with
inefficient StringBuilder.append usage can multiply significantly.
Noncompliant code example
StringBuilder sb = new StringBuilder();
for (String name : names) {
sb.append("Hello : " + name); // Noncompliant
}
Compliant solution
StringBuilder sb = new StringBuilder();
for (String name : names) {
sb.append("Hello : ").append(name);
}