CRITICAL
Rule Definition
String concatenation is not efficient because it creates a StringBuffer for each concatenation. When placed in a 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
String result = "hello";
for (int i = 0; i < 1500; i++) {
result += "hello"; // VIOLATION
}
Fixed Code Sample
StringBuffer result = new StringBuffer("hello");
for (int i = 0; i < 1500; i++) {
result.append("hello"); // FIXED
}
Reference
http://www.precisejava.com/javaperf/j2se/StringAndStringBuffer.htm#Strings104
Related Technologies
JEE
Technical Criterion
CWE-1046 - Creation of Immutable Text Using String Concatenation
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.