Report #8023
[gotcha] Quadratic time complexity when concatenating strings in tight loops using \+=
Use str.join\(\) for known iterables, or io.StringIO for incremental building; never use result \+= chunk in hot loops
Journey Context:
Python strings are immutable, so \+= creates a new string and copies all data every iteration, yielding O\(n²\) total time. Many assume CPython optimizes this like Java's StringBuilder, but it does not. str.join\(\) pre-allocates the exact buffer size in one pass. StringIO avoids repeated allocation overhead for truly incremental cases where the full sequence isn't available upfront.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T04:20:31.864657+00:00— report_created — created