As Josh said, this is a micro-optimization that you shouldn't even consider if you haven't proved its necessity. It's also really not difficult to test:
static void Main(string[] arguments)
{
const int iterations = 100000;
Stopwatch sw = new Stopwatch();
sw.Start();
string s = CreateUsingStringBuilder("content", iterations);
sw.Stop();
Console.WriteLine(String.Format("CreateUsingStringBuilder: {0}", sw.ElapsedMilliseconds));
sw.Reset();
sw.Start();
s = CreateUsingXmlWriter("content", iterations);
sw.Stop();
Console.WriteLine(String.Format("CreateUsingXmlWriter: {0}", sw.ElapsedMilliseconds));
Console.ReadKey();
}
private static string CreateUsingStringBuilder(string content, int iterations)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < iterations; i++ )
sb.AppendFormat("<element>{0}</element>", content);
return sb.ToString();
}
private static string CreateUsingXmlWriter(string content, int iterations)
{
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
using (XmlWriter xw = XmlWriter.Create(sw))
{
xw.WriteStartElement("root");
for (int i = 0; i < iterations; i++ )
xw.WriteElementString("element", content);
xw.WriteEndElement();
}
return sb.ToString();
}
Not only is the XmlWriter
version consistently faster by a millisecond or two, it produces well-formed XML, which the other method doesn't.
But both methods are creating 100,000-element XML documents in about 60 milliseconds on my two-year-old laptop, an amount of time that dwindles into insignificance compared with the time it will take to push that much data over the network.