We test the general performance of string.Join. This method appears to have excellent performance. We see that string.Join performs well—often better than loops.
using System;
using System.Diagnostics;
class Program
{
static string CombineA(string[] arr)
{
return string.Join(
",", arr);
}
static string CombineB(string[] arr)
{
var builder = new System.Text.StringBuilder();
foreach (string s in arr)
{
builder.Append(s).Append(
",");
}
return builder.ToString();
// Has ending comma.
}
const int _max = 1000000;
static void Main()
{
string[] arr = {
"one",
"two",
"three",
"four",
"five" };
var s1 = Stopwatch.StartNew();
// Version 1: use string.Join.
for (int i = 0; i < _max; i++)
{
if (CombineA(arr).Length == 0)
{
return;
}
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use StringBuilder.
for (int i = 0; i < _max; i++)
{
if (CombineB(arr).Length == 0)
{
return;
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
}
}
58.42 ns string.Join
122.52 ns StringBuilder, Append, ToString