تخطَّ إلى المحتوى

String concat in loop (ARCH2070)

هذا المحتوى غير متوفر بلغتك بعد.

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

Strings are immutable, so accumulating with += in a loop builds a new copy each iteration, yielding O(n²) cost. Collect parts in a list and join once at the end.

def render(items):
out = ""
for item in items:
out += str(item) + ","
return out
def render(items):
parts = [str(item) for item in items]
return ",".join(parts) + "," if parts else ""

Collect fragments in a list and combine them in one pass with "".join(...) after the loop.