String Concatenation in Loop
ID |
java.string_concat_in_loop |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
code-style |
Description
Reports String concatenation using the + or += operator inside loop bodies. Each concatenation creates a new String object, leading to O(n^2) memory allocations.
Rationale
Java strings are immutable. Every + concatenation allocates a new String and copies the accumulated characters. Inside a loop, this turns a linear operation into a quadratic one.
// Bad — quadratic allocation
String result = "";
for (String item : items) {
result += item;
}
Remediation
Use StringBuilder (or StringJoiner / String.join() when joining with a delimiter):
// Good — linear allocation
StringBuilder sb = new StringBuilder();
for (String item : items) {
sb.append(item);
}
String result = sb.toString();