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文件?

谢谢。

+0

尝试使用XPathNavigator对象 - http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx – 2010-08-26 21:50:14

+1

XmlTextReader是一个Disposable对象。 – 2010-08-26 21:51:43

+1

@Yuriy,你的意思是使用reader.close()?我这样做,只是没有包含在上面的代码片段中。 – Radu 2010-08-26 21:55:17

,所以我不认为这是在让我

要确认下载时间这个你有没有考虑在本地下载的文件,然后看到什么时间就像

+1

不,现在就开始尝试。感谢您的建议! – Radu 2010-08-26 21:57:32

+0

从1000ms降至1ms。猜猜我被搞砸了。不敢相信我没有想过要测试这个 - 谢谢! – Radu 2010-08-26 22:02:37

我想你正在测量创建连接所花费的时间。要确认这一点,您可以将Reset + Start(重置+起始)行移动到读取器创建的上方。我预计会有很少或没有差异。

如果是连接时间,则取决于网络,并且您可以在代码中进行注意。也许你可以通过tweeking你的网络设置得到一些改进。但那是另一个论坛。

+0

我移动了秒表以包围读者的声明,它读取0. – Radu 2010-08-26 21:57:50

+1

我认为确认。它表示,XmlReader是读取Xml的最快方式。这是一个I/O问题。 – 2010-08-26 22:00:56

+2

因此,直到您启动Read()'ing时才会建立连接 - 那么您将遇到TCP握手,然后是TCP慢启动。如果您要在app生命周期中多次获取流,请查看您是否可以保持持久的HTTP连接对服务器开放。 – snemarch 2010-08-26 22:03:31

尝试设置

reader.XmlResolver = null; 
+0

似乎没有帮助,虽然我可能需要做很多迭代才能确定。 – Radu 2010-08-26 21:57:08

我比较了你的方法和另一个方法。只需下载数据并通过正则表达式查找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是更好:) 。