typestar

StringBuilder in C#

Strings are immutable, so repeated concatenation copies; a builder does not.

using System.Text;

// strings are immutable; a builder makes many appends cheap
var sb = new StringBuilder();
for (int i = 1; i <= 5; i++)
{
    sb.Append("step ").Append(i).AppendLine();
}
sb.Insert(0, "the plan:\n");
Console.WriteLine(sb.ToString());
Console.WriteLine($"length {sb.Length}");

How it works

  1. Append and AppendLine grow the buffer in place.
  2. Insert(0, ...) writes at any position, even the front.
  3. ToString() pays the string cost once, at the end.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
291
Tokens
71
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 45 seconds.

Type this snippet

Step 4 of 4 in Strings, step 7 of 29 in Language basics.

← Previous Next →

StringBuilder in other languages