Rule Definition
String concatenation is not efficient because it creates a StringBuffer for each concatenation. When placed in an indirect loop, String concatenation results in the creation and garbage collection of large numbers of temporary objects. This both consumes memory and can dramatically slow the program execution. It is recommended to create a StringBuffer before entering the loop, and append to it within the loop, thus reducing the overhead.
Remediation
It is recommended to create a StringBuilder (if JDK >= 1.5 and not in thread environment) or StringBuffer before entering the loop, and append to it within the loop, thus reducing the overhead.
Violation Code Sample
public class ConcatenationTest {
public String concatString(String name) {
String result = "hello ";
result += name;
return result
}
}
public class LoopTest {
static final int N = 18000000;
private ConcatenationTest ct = new ConcatenationTest();
public void myLoop(void) {
String name = "bob";
for (int i = 1; i <= N; i++) {
ct.concatString(name); // VIOLATION
}
}
}
Fixed Code Sample
public class ConcatenationTest {
public void concatString(StringBuffer result, String name) {
result.append(name);
}
}
public class LoopTest {
static final int N = 18000000;
private ConcatenationTest ct = new ConcatenationTest();
public void myLoop() {
StringBuffer result = "hello";
String name = "bob";
for (int i = 1; i <= N; i++) {
ct.concatString(result, name); // FIXED
}
}
}
Reference
http://www.precisejava.com/javaperf/j2se/StringAndStringBuffer.htm#Strings104
Related Technologies
Technical Criterion
Efficiency - Expensive Calls in Loops
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.