Overview
- A StringBuilder maintains an internal buffer instead of allocating a new string every time.
- Initial buffer size is 16 characters, but can be passed via the constructor.
- Use a StringBuilder when appending lots of strings.
Good practice
- Use StringBuilder when doing a lot of string manipulation.
- See String Concatenation vs Memory Allocation for detailed analysis of string operations.
- Try to estimate the initial size for a StringBuilder whenever possible; this avoids unneeded buffer growth.
Examples
Concatenating
public string GetBuildString()
{
StringBuilder builder = new StringBuilder();
builder.Append("SELECT column1,");
builder.Append(" column2,");
builder.Append(" column3,");
builder.Append(" column4,");
builder.Append(" column5,");
builder.Append(" column6");
builder.Append(" FROM table1 t1");
builder.Append(" JOIN table2 t2");
builder.Append(" ON t1.column1 = t2.column1");
return builder.ToString();
}
You May Also Like

Exam 70-536 Study Notes
My study notes for Microsoft exam 70-536: .NET types, collections, generics, I/O, serialization and more, with C# examples.

Starting Exam 70-536 Study
After a burnout, I'm putting my own project on hold to study for Microsoft exam 70-536.

Design Patterns - Proxy Pattern
The Proxy Pattern, and the last article in the design patterns series, now that I've finished reading Head First Design Patterns.




