Back to results for “Memory Management”
C++ › Strings & string_view

How do you efficiently build up a large string?

Intermediate

Answer

Repeated + concatenation can cause many reallocations. Efficient approaches: reserve() the expected capacity up front, use += (append in place), use a std::ostringstream for formatted assembly, or std::string::append. Reserving capacity avoids repeated growth-and-copy, which dominates naive concatenation performance.
std::string s;
s.reserve(1000);          // avoid reallocations
for (auto& part : parts) s += part;
Real-world example Reserving capacity before a build loop turns O(n^2) reallocation into a single allocation.

Common follow-ups: Why does reserve help? | What does ostringstream offer?