CRITICAL
Rule Definition
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 StringBuilder before entering the loop, and append to it within the loop, thus reducing the overhead.
Remediation
It is recommended to create a StringBuilder before entering the loop, and append to it within the loop, thus reducing the overhead.
Violation Code Sample
static void LoopKO()
{
String myText = "hello" ;
for(int i = 0; i < 1000; i++)
{
myText += "count ="; // VIOLATION
myText += i.ToString(); // VIOLATION
}
Console.WriteLine(myText.ToString());
}
Fixed Code Sample
static void LoopOK()
{
StringBuilder myText = new StringBuilder();
for(int i = 0; i < 1000; i++)
{
myText.Append("count ="); // FIXED
myText.Append(i.ToString()); // FIXED
}
Console.WriteLine(myText.ToString());
}
Reference
CISQ rule: ASCPEM-PRF-2.
Related Technologies
.Net
Technical Criterion
CWE-1095 - Loop Condition Value Update within the 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.