StringBuffer/StringBuilder for Constant Value

ID

java.stringbuffer_for_constant_value

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Java

Tags

best-practice, efficiency

Description

Reports local StringBuffer or StringBuilder variables that are never mutated. When no mutator method (append, insert, delete, replace, reverse, setCharAt, setLength, deleteCharAt, appendCodePoint) is called on the variable, a plain String would suffice and avoids the overhead of maintaining a mutable buffer object.

Rationale

String objects are immutable and cheap to create, while StringBuffer and StringBuilder carry the overhead of a resizable character array and synchronization (for StringBuffer). If the buffer is never modified after construction, using it is wasteful.

// Bad -- StringBuffer is never mutated
StringBuffer sb = new StringBuffer("Hello");
String result = sb.toString();

Remediation

Replace the StringBuffer/StringBuilder with a plain String.

// Good -- use String directly
String result = "Hello";