c# – StringBuilder与XmlTextWriter

前端之家收集整理的这篇文章主要介绍了c# – StringBuilder与XmlTextWriter前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图从提供Xml内容自定义HttpHandler中尽可能多地提高性能.

我想知道哪个更好的性能.使用XmlTextWriter类或ad-hoc StringBuilder操作,如:

StringBuilder sb = new StringBuilder("<?xml version="1.0" encoding="UTF-8" ?>");    
sb.AppendFormat("<element>{0}</element>",SOMEVALUE);

有没有人有第一手经验?

解决方法

正如约什所说,这是一个微观优化,如果你没有证明它的必要性,你甚至不应该考虑.测试也非常困难:
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();
}

XmlWriter版本不仅速度提高了一两毫秒,而且还可以生成格式良好的XML,而另一种方法则不然.

但是这两种方法在我两年前的笔记本电脑上在大约60毫秒内创建了100,000个元素的XML文档,与通过网络推送大量数据所需的时间相比,这个时间缩短到了无足轻重的程度.

猜你在找的C#相关文章