0 day streak
csharp / beginner
Snippet

Concatenation with StringBuilder

StringBuilder is significantly more efficient than using '+' for strings in loops because it doesn't create new objects in memory for every change.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
using System.Text;
public class DataFormatter {
public string FormatList(string[] items) {
var sb = new StringBuilder();
foreach (var item in items) {
sb.Append("Item: ").Append(item).AppendLine();
}
return sb.ToString();
}
}
Breakdown
1
var sb = new StringBuilder();
Creates a mutable buffer for building strings efficiently.
2
sb.Append("Item: ")
Adds text to the existing buffer without creating a new string instance.