StringBuilder is a mutable character sequence for assembling strings through repeated appends. It avoids repeatedly copying the growing result, replacing accidentally quadratic concatenation with linear construction in the scenarios described here. section 1.2.1 section 9.3.4
Use StringBuilder when construction repeatedly extends or temporarily modifies a result:
- Build a large string by appending many small fragments, such as text emitted by a pretty printer. section 9.3.4
- Carry a changing prefix while traversing a trie, converting it to a string only when yielding a completed word. section 5.2.3
- Reset the builder after recursive traversal so sibling branches reuse the same prefix storage. section 5.2.3
Pretty-printing and trie traversal
A nonrecursive pretty printer creates a StringBuilder, appends text fragments, line breaks, and indentation while processing an explicit work stack. A trie-backed word list instead initializes the builder with a prefix, appends edge characters during traversal, yields prefix.ToString() at word endings, and restores the prior state before returning. section 9.3.4 section 5.2.3
Listing 9.4 A nonrecursive Pretty method
using System.Text;
abstract record class Doc
{
// […]
public string Pretty(int width)
{
var sb = new StringBuilder();
int used = 0; #1
var docs = new Stack<(bool, int, Doc)>(); #2
docs.Push((true, 0, new GroupDoc(this))); #3
while (docs.Count > 0) #4
{
(bool fits, int indent, Doc doc) = docs.Pop(); #5
switch (doc)
{
case TextDoc td:
sb.Append(td.text); #6
used += td.text.Length;
break;
case GroupDoc gd: #7
docs.Push((gd.doc.Fits(width - used), indent, gd.doc));
break;
case IndentDoc id: #8
docs.Push((fits, indent + IndentSpaces, id.doc));
break;
case OptBreakDoc bd:
if (fits) #9
{
sb.Append(bd.text);
used += bd.text.Length;
}
else #10
{
sb.AppendLine();
sb.Append(' ', indent);
used = indent;
}
break;
case ConcatDoc cd: #11
docs.Push((fits, indent, cd.right));
docs.Push((fits, indent, cd.left));
break;
}
}
return sb.ToString();
} }
Inspect the complete C# implementation showing StringBuilder alongside the explicit stack, fit decisions, indentation, and document cases. section 9.3.4

