Skip to content

String Concat In Loop (ARCH3070)

Key typescript.performance.string-concat-in-loop · Severity warning · Category performance

Accumulating a string with += inside a loop allocates a new string and copies the characters on every iteration, producing O(n^2) cost as input grows.

function join(items: string[]): string {
let result = "";
for (const item of items) {
result += item + ",";
}
return result;
}
function join(items: string[]): string {
const parts: string[] = [];
for (const item of items) {
parts.push(item);
}
return parts.join(",");
}

Collect the pieces in an array and join them once after the loop with join.