Avoid indirect String concatenation inside loops | CAST Appmarq

Avoid indirect String concatenation inside loops


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
JEE

Health Factor

  Total Quality Index


Technical Criterion
CWE-1050 - Excessive Platform Resource Consumption within a Loop

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

86.23%

Total Violations
200,445
Total Opportunities
1,455,306
Average Violations / App.
237.21
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

Software ISV

77.13%

Financial Services

86.11%

Telecommunications

70.61%