csharp / beginner
Snippet
Efficient Loop Buffering
Using StringBuilder is significantly faster than standard string concatenation (+) when modifying text inside a loop.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
using System.Text;public class Program {public static void Main() {StringBuilder sb = new StringBuilder();for (int i = 0; i < 5; i++) {sb.Append("Item ").Append(i).Append(" ");}System.Console.WriteLine(sb.ToString());}}
Breakdown
1
StringBuilder sb = new StringBuilder()
Initializes a mutable string buffer to store characters efficiently.
2
sb.Append(i)
Adds the current value to the end of the buffer without creating a new string object.