问题描述
我要挤尽可能多的表现,我可以从一个自定义的HttpHandler供应XML内容。
I am trying to squeeze as much performance as i can from a custom HttpHandler that serves Xml content.
我想知道这是更好的性能。使用XmlTextWriter类或临时StringBuilder的操作,如:
I' m wondering which is better for performance. Using the XmlTextWriter class or ad-hoc StringBuilder operations like:
StringBuilder sb = new StringBuilder("<?xml version="1.0" encoding="UTF-8" ?>");
sb.AppendFormat("<element>{0}</element>", SOMEVALUE);
有没有人有第一手的经验?
Does anyone have first hand experience?
推荐答案
由于乔希说,这是,如果你还没有证明其必要性,你应该甚至不考虑微的优化。它也确实不难测试:
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();
}
不仅是的XmlWriter
版本始终由一个或两个毫秒的速度更快,它产生格式良好的XML,这另一种方法则没有。
Not only is the XmlWriter
version consistently faster by a millisecond or two, it produces well-formed XML, which the other method doesn't.
不过,这两种方法都创造10万XML元素文件在我二十岁的笔记本电脑,那不断下降微不足道与它会通过网络推这么多数据的时间相比,时间量大约60毫秒。
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.
这篇关于StringBuilder的VS的XmlTextWriter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!