String Concatenation In Loop

ID

kotlin.string_concat_in_loop

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

Kotlin

Tags

performance, string

Description

Reports += on a String variable inside a loop body.

Each s += x statement inside a loop allocates a new String by copying the old content and appending the new fragment. Over n iterations this produces O(n) allocations and O(n²) total character copying, degrading performance proportionally to the total length of the accumulated string.

Rationale

// Bad — new String allocated on every iteration
var result = ""
for (item in items) {
    result += item   // FLAW
}

// Good — StringBuilder (imperative)
val sb = StringBuilder()
for (item in items) {
    sb.append(item)
}
val result = sb.toString()

// Good — joinToString (functional, no loop needed)
val result = items.joinToString("")

Remediation

  • Replace the accumulation loop with joinToString() when building a single joined string.

  • Use StringBuilder and append() when the loop body applies conditional or complex logic before appending each fragment.

References