Avoid String concatenation in loops | CAST Appmarq

Avoid String concatenation in loops

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

Health Factor

  Efficiency


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.

Benchmark Statistics

Global Compliance

99.61%

Total Violations
129,472
Total Opportunities
32,944,561
Average Violations / App.
91.05
The compliance score represents 1 minus the ratio between the number of times a rule has been violated compared to the number of opportunities in a set of applications that the rule could have been violated.

Industry Insights

Financial Services

99.54%

Telecommunications

99.30%

Insurance

99.77%