0 day streak
csharp / beginner
Snippet

Fast String Construction

Strings in C# are immutable. For large-scale concatenation, using StringBuilder is much more efficient because it modifies a single internal buffer instead of creating many temporary strings.

snippet.cs
csharp
1
2
3
4
5
var builder = new System.Text.StringBuilder();
for (int i = 0; i < 100; i++)
{
builder.Append("Item ").Append(i).Append(" ");
}
Breakdown
1
var builder = new System.Text.StringBuilder();
Initializes a new mutable string builder instance.
2
builder.Append("Item ").Append(i)
Adds text to the end of the current buffer efficiently.