StringBuilder Class

Overview

  • A StringBuilder maintains an internal buffer instead of allocating a new string every time.
  • Initial buffer size is 16 bytes, but can be passed via the constructor.
  • Use a StringBuilder when appending lots of strings.

Good practice

  • Use StringBuilder when excessively working with strings.
  • Try to estimate the initial size for a StringBuilder whenever possible, this will avoid unneeded buffer growths.

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();
}