Skip to main content

Anti-Pattern: String Concatenation in Loops

Description​

Using the += operator to concatenate strings inside a loop. Since strings are immutable in C#, this creates a new string object for every iteration, copying the old content plus the new content.

Impact​

  • Performance: O(N²) complexity for memory allocation and copying.
  • Memory: Heavy pressure on the Garbage Collector (GC) due to thousands of temporary objects.

Detection​

Loops containing str += ... or str = str + ....

// āŒ BAD: Creates N string objects
string summary = "";
foreach (var item in items) {
summary += item.Name + "<br/>";
}

Refactoring​

Use StringBuilder for loop-based concatenation.

// āœ… GOOD: Allocates a buffer and expands only when needed
StringBuilder sb = new StringBuilder();
foreach (var item in items) {
sb.Append(item.Name).Append("<br/>");
}
string summary = sb.ToString();

2026 Audit Findings​

  • Occurrences: > 2,000 candidates.
  • Severity: Medium (Critical in Hot Paths).
  • Key Locations:
    • TravelTicketProposalOMGT.cs (Manual HTML building)
    • OrderTravelProductOMGT.cs (Log text construction)