XML阅读器性能
问题描述:
我已经在我的应用程序中追溯到下面定时定位的代码段落。我知道这会是一个慢点,但每个请求平均需要1秒。我后面的xml位总是在第一个标签中,所以我不认为这是下载时间让我感到满意。XML阅读器性能
Stopwatch stopwatch = new Stopwatch();
XmlTextReader reader = new XmlTextReader("http://steamcommunity.com/id/test?xml=1");
stopwatch.Reset();
stopwatch.Start();
while (reader.Read()) {
if (reader.Name.Equals("steamID64")) {
reader.Read();
stopwatch.Stop();
time = stopwatch.ElapsedMilliseconds();
return Convert.ToInt64(reader.Value);
}
}
是否有更快的方式来读取我想要的标签或我被服务器限制我正在下载xml文件?
谢谢。
答
我想你正在测量创建连接所花费的时间。要确认这一点,您可以将Reset + Start(重置+起始)行移动到读取器创建的上方。我预计会有很少或没有差异。
如果是连接时间,则取决于网络,并且您可以在代码中进行注意。也许你可以通过tweeking你的网络设置得到一些改进。但那是另一个论坛。
答
我比较了你的方法和另一个方法。只需下载数据并通过正则表达式查找id。
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Reset();
stopwatch.Start();
System.Net.WebClient wc = new System.Net.WebClient();
string s = wc.DownloadString("http://steamcommunity.com/id/test?xml=1");
System.Text.RegularExpressions.Regex re = new Regex("\\<steamID64\\>(\\d+)\\</steamID64\\>");
System.Text.RegularExpressions.Match m = re.Match(s);
if (m != null && m.Captures.Count != 0) Response.Write("steamID64: " + m.Captures[0].Value + " <br/>");
stopwatch.Stop();
long time = stopwatch.ElapsedMilliseconds;
Response.Write("Time Elapsed (1):" + time.ToString() +" <br/>");
stopwatch.Reset();
stopwatch.Start();
System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("http://steamcommunity.com/id/test?xml=1");
stopwatch.Reset();
stopwatch.Start();
while (reader.Read())
{
if (reader.Name.Equals("steamID64"))
{
reader.Read();
stopwatch.Stop();
time = stopwatch.ElapsedMilliseconds;
s = reader.Value;
break;
}
}
Response.Write("<br/>steamID64: " + s);
Response.Write("<br/>Time Elapsed (2):" + time.ToString() + " <br/>");
**结果:
steamID64:76561197991558078 运行时间(1):1572
steamID64:76561197991558078 运行时间(2):969
的XmlReader是更好:) 。
尝试使用XPathNavigator对象 - http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx – 2010-08-26 21:50:14
XmlTextReader是一个Disposable对象。 – 2010-08-26 21:51:43
@Yuriy,你的意思是使用reader.close()?我这样做,只是没有包含在上面的代码片段中。 – Radu 2010-08-26 21:55:17