Doing some perf testing, String::Join vs StringBuilder::Append...
I just posted this to a newsgroup, however, it is a question I've been asking myself for a while. When is it appropriate to use a String::Join and when to use a StringBuilder::Append? I'm sure there are plenty of times where the StringBuilder really comes in handy. Especially when you can't collect all of your strings together into a single array. However, when you have the array and you need to quickly build a new joined string, String::Join comes to the rescue. I've created a sample program along with the timings on my machine. Here is the newsgroup article as posted:
String.Join is implemented internally by the run-time. It is serviced by the
ConcatenateJoinHelperArray method which turns out to be extremely fast at
creating the final string as opposed to the slightly slower
StringBuilder.Append. If you have an array of strings, I would recommend using
that with String.Join over StringBuilder.Append since String.Join is going to be
quite a bit faster.
using System;
using System.Text;
public class JoinVsBuilder {
private static string[] strings = new string[0];
private static void Main(string[] args) {
int count = int.Parse(args[0]);
strings = new string[count];
for(int i = 0; i < count; i++) {
strings[i] = i.ToString();
}
DateTime start, end;
start = DateTime.Now;
string newStr = string.Join("foo", strings);
end = DateTime.Now;
Console.WriteLine("String::Join timing is {0}", end-start);
StringBuilder sb = new StringBuilder();
start = DateTime.Now;
// Faster than worrying about when to append the connector
sb.Append(strings[0]);
for(int i = 1; i < strings.Length; i++) {
sb.Append("foo");
sb.Append(strings[i]);
}
string newStr2 = sb.ToString();
end = DateTime.Now;
Console.WriteLine("StringBuilder::Append timing is {0}", end-start);
}
}
C:\Projects\CSharp\Samples\JoinVsBuilder>JoinVsBuilder.exe 1000000
String::Join timing is 00:00:00.4606624
StringBuilder::Append timing is 00:00:02.9141904
That is pretty much all I have for right now. Hopefully I haven't been less than rigorous in my testings. I don't feel that I've given StringBuilder::Append a bad shake since there are proper times to use it. Just don't use it when you already have your values ready to go since a String::Join can be quite a bit faster.