C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
With the appropriate StringBuilder Append overload, we append a part of another string. This eliminates extra string copies and improves performance.
Example. In Method1, we take a substring of the input string and then append that to the StringBuilder. In Method2, we call Append with three arguments. This is equivalent to the Substring call but much faster.
Tip: Often you do not need to call Substring before calling Append. We can append just a range.
C# program that uses StringBuilder overload using System; using System.Diagnostics; using System.Text; class Program { static void Method1(string input, StringBuilder buffer) { buffer.Clear(); string temp = input.Substring(3, 2); buffer.Append(temp); } static void Method2(string input, StringBuilder buffer) { buffer.Clear(); buffer.Append(input, 3, 2); } static void Main() { const int m = 100000000; var builder = new StringBuilder(); var s1 = Stopwatch.StartNew(); for (int i = 0; i < m; i++) { Method1("deves", builder); } s1.Stop(); var s2 = Stopwatch.StartNew(); for (int i = 0; i < m; i++) { Method2("deves", builder); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / m).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / m).ToString("0.00 ns")); Console.Read(); } } Output 33.47 ns 25.14 ns
The StringBuilder Append version that avoids a separate Substring call is faster. Thus, in situations where you have an input string and want to append a substring to your StringBuilder, using this overload is the best solution.
I have found that eliminating string allocations is often a highly effective way to improve C# program performance. It improves execution speed. It also reduces the need to collect garbage. Fewer objects are created, and fewer die.
Summary. The StringBuilder type is purely an optimization for string operations. Programs that use StringBuilder are in the process of optimization. They may call the Substring method before appending.
But: This is inefficient and can be eliminated with the correct Append method overload.