String is built by repeated concatenation inside a loop

ID

vbnet.performance.string_concat_in_loop

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

String Handling

Language

VB.NET

Description

A String variable is grown by repeated concatenation (&, &= or +=) inside a For, For Each, While or Do loop, so the accumulator is rebuilt on every iteration.

Rationale

NET strings are immutable, so each concatenation allocates a brand-new string and copies every character accumulated so far. Over N iterations the loop performs O(N^2) character copies and leaves N-1 dead intermediate strings for the garbage collector. On a short list this is invisible; on a few thousand rows — building HTML, CSV or a log payload — it turns a linear operation into a measurable stall and a burst of gen-0 pressure.

The following code illustrates the pattern detected by this rule:

Public Function ToCsv(ByVal rows As List(Of String())) As String
    Dim csv As String = String.Empty
    For Each row As String() In rows
        ' FLAGGED: String is built by repeated concatenation inside a loop
        csv &= String.Join(",", row) & Environment.NewLine
    Next
    Return csv
End Function

Remediation

Accumulate into a System.Text.StringBuilder declared before the loop and call .Append(…​) (or .AppendLine(…​)) inside it, then read the result once with .ToString() after the loop. For the common case of joining a sequence with a separator, String.Join(",", values) is clearer still and needs no loop at all.

Configuration

This detector does not need any configuration.