İçeriğe geç

Döngüde String Birleştirme (ARCH3070)

Anahtar typescript.performance.string-concat-in-loop · Önem warning · Kategori performance

Döngü içinde += ile string biriktirmek her yinelemede yeni bir string tahsis eder ve karakterleri kopyalar; bu da girdi büyüdükçe O(n^2) maliyet üretir.

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(",");
}

Parçaları bir diziye toplayıp döngü sonunda tek seferde join ile birleştirin.