Glossary / StringBuilder
StringBuilder
StringBuilder is a mutable character buffer for constructing strings through repeated appends, inserts, and replacements. It can avoid repeated intermediate string allocations in loops or complex assembly, but it is not automatically faster than interpolation or concatenation for small/fixed expressions.
Growth and output
var builder = new StringBuilder();
foreach (var item in items) builder.Append(item).Append(',');
string result = builder.ToString();
The builder maintains a capacity that can grow as needed; setting an estimated capacity can reduce reallocations for known large outputs. ToString() creates an immutable string copy. Clear() resets logical content but can retain allocated capacity. Builders are mutable and not thread-safe; do not share one concurrently without synchronization.
Use AppendLine with awareness of environment-specific newline behavior. Formatting overloads can depend on culture; specify CultureInfo.InvariantCulture for protocol or machine-readable output. For fixed interpolation, compiler optimizations and string.Create/interpolated-string handlers can be efficient; benchmark actual patterns.
Engineering guidance
Use StringBuilder for loops or incremental construction with many pieces. Avoid pooling builders unless profiling demonstrates a benefit and retention/cross-request data risks are handled. Do not use it to build SQL/HTML without parameterization or escaping; builder does not prevent injection.
Interview questions
- Why use StringBuilder in a loop? It can reduce repeated immutable string allocations/copies.
- Is it always faster? No; simple concatenation/interpolation may be optimized.
- What does
ToString()cost? It materializes a new string containing the buffer contents. - Is it thread-safe? No.
- Does it prevent injection? No; use parameterized queries and context-aware encoding.