csharp / beginner
Snippet
Reducing Memory Allocations in Loops
Regular strings in C# are immutable. Using StringBuilder is much more efficient for performance when concatenating many strings together in a loop.
snippet.cs
csharp
1
2
3
4
5
6
7
using System.Text;var builder = new StringBuilder();for (int i = 0; i < 100; i++) {builder.Append("Step ").Append(i).Append("; ");}string finalPath = builder.ToString();
Breakdown
1
new StringBuilder()
Creates a single mutable buffer that can be expanded without creating new objects.
2
builder.Append(...)
Modifies the existing buffer instead of allocating a new string in memory.