Avoid String concatenation in loops for artifacts with high fan in | CAST Appmarq

Avoid String concatenation in loops for artifacts with high fan in


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. When the artifacts have a high fan-in the risk is highly increased.

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

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.72%

Total Violations
3
Total Opportunities
1,085
Average Violations / App.
1.50
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

Select from drop-down

99.87%

Financial Services

99.69%

Insurance

99.64%