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
AppendandAppendLinegrow the buffer in place.Insert(0, ...)writes at any position, even the front.ToString()pays the string cost once, at the end.
Keywords and builtins used here
forintnewusingvar
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.
Step 4 of 4 in Strings, step 7 of 29 in Language basics.