To build large strings efficiently in Python, collect the pieces in a list and join them once with "".join(parts), or write them into an io.StringIO buffer and call getvalue() at the end. Both approaches take time proportional to the final length. Repeated += on a string can degrade toward quadratic time, because strings are immutable and each concatenation may copy everything built so far.
This matters for python string performance whenever you assemble reports, CSV or JSON output, templates, or log lines from thousands or millions of fragments. The examples target Python 3.13 and 3.14.
"".join()io.StringIO bufferA str is immutable. The expression s = s + piece creates a new string object, copies the old contents and the new piece into it, and then drops the old one. Building a string of n pieces this way copies roughly 1 + 2 + ... + n pieces worth of characters, which is quadratic work.
CPython has an optimisation that can resize a string in place when the left operand has a reference count of one. It makes the loop above fast in many simple cases, but it is an implementation detail of CPython, it does not apply to attributes, dictionary values or list items, and it is not guaranteed on other implementations such as PyPy. Do not build code that depends on it.
"".join()str.join takes any iterable of strings. It first measures the total length, allocates the result once, and copies each piece a single time.
A generator expression works as well, although join converts it to a list internally so it can compute the size first:
Two points to remember:
str. "".join([1, 2]) raises TypeError, so convert with str(x) or an f-string."\n".join(lines) + "\n" when you need a trailing newline.io.StringIO bufferio.StringIO is an in-memory text file. It is the better choice when the code that produces text expects a file-like object, for example print(..., file=buf), csv.writer(buf), json.dump(obj, buf) or a template renderer.
StringIO appends to an internal buffer with amortised constant cost per write. Call getvalue() once at the end, because each call produces a full copy of the content. If you only need to stream the output to a real file or a socket, skip the buffer and write to that destination directly.
The right tool depends on how you produce the text.
| Approach | Time to build | Best for | Watch out for |
|---|---|---|---|
s += piece in a loop | Can be quadratic | A handful of pieces | Slow on large inputs, behaviour differs across implementations |
list.append then "".join | Linear | Pieces you already have or generate in a loop | Items must be str |
io.StringIO | Linear | Code that writes to a file-like object | Do not call getvalue() repeatedly |
f-string or str.format | Constant for one string | Small fixed templates | Not a loop tool |
bytearray or io.BytesIO | Linear | Binary data, or text you will encode anyway | Decode at the end if you need str |
Do not trust a rule of thumb for your workload. Measure with timeit:
On a typical CPython build with_join is the fastest because it runs almost entirely in C, with_stringio is close behind, and with_plus falls behind as N grows, or when you move the accumulator out of a local variable. Exact numbers depend on your machine and Python version, so run it yourself. Pass a much larger N and watch how the three curves diverge.
Python stores a str using one, two or four bytes per character depending on the widest character it contains (the flexible string representation from PEP 393). One non-Latin-1 character in a huge ASCII text makes the whole string use two bytes per character or more. If you join mostly ASCII text with a few emoji, the result is larger than you might expect.
Peak memory during "".join(parts) is roughly the size of all the pieces plus the final string, because both exist at once. For output that does not fit comfortably in memory, stream instead: write each chunk to a file, sys.stdout or a network socket as you produce it, or yield chunks from a generator and let the consumer decide.
When you build bytes rather than text, use b"".join(chunks), io.BytesIO or a bytearray with extend. Do not encode piece by piece into a str and encode at the end if the destination wants bytes.
+= always slower than join?No. For a few pieces the difference is negligible, and CPython can optimise simple local += loops. It becomes a problem with many pieces, with accumulators stored in attributes or containers, or on other implementations.
join?An f-string builds one string from a fixed set of values, so it is the best way to format a single line. It does not replace join for a variable number of pieces.
StringIO or a list with join?Use a list and join when you have plain strings. Use StringIO when a library needs a file-like object to write into, or when you prefer the write and print(file=...) style.
Do not build it at all. Write chunks to a file or socket as you generate them, or expose a generator, so only a small part is in memory at a time.
Avoid growing a string with += in a long loop. Collect pieces in a list and call "".join once, or write to an io.StringIO and call getvalue() once. Convert items to str first, stream when the output is too big for memory, and confirm the choice with timeit on your own data.