0 day streak
csharp / beginner
Snippet

Large String Construction Speed

In C#, strings are immutable, meaning they cannot be changed. Using '+' in a loop creates many temporary objects. StringBuilder provides a mutable buffer that significantly improves performance for large text operations.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
using System.Text;
public class TextProcessor {
public string JoinWords(string[] words) {
// StringBuilder is more efficient than normal string concatenation in loops
var sb = new StringBuilder();
foreach (var word in words) {
sb.Append(word).Append(" ");
}
return sb.ToString().Trim();
}
}
Breakdown
1
new StringBuilder()
Creates an object optimized for building and modifying strings.
2
sb.Append(word)
Adds content to the end of the buffer without creating a new string object.