
A substring can be appended with StringBuilder. With the appropriate StringBuilder Append overload, we append a part of another string. This eliminates extra string copies and improves performance.
Tip: Often you do not need to call Substring before calling Append.
This program is both an example of Append and also a benchmark. 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.
Program that uses StringBuilder overload [C#]
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("perls", builder);
}
s1.Stop();
var s2 = Stopwatch.StartNew();
for (int i = 0; i < m; i++)
{
Method2("perls", 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 nsResults. The StringBuilder Append version that avoids a separate Substring call is much 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.
Substring Examples
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. This is inefficient and can be eliminated with the correct Append method overload.
StringBuilder Secrets