2010-08-26 82 views
1

我已經在我的應用程序中追溯到下面定時定位的代碼段落。我知道這會是一個慢點,但每個請求平均需要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

,所以我不認爲這是在讓我

要確認下載時間這個你有沒有考慮在本地下載的文件,然後看到什麼時間就像

+1

不,現在就開始嘗試。感謝您的建議! – Radu 2010-08-26 21:57:32

+0

從1000ms降至1ms。猜猜我被搞砸了。不敢相信我沒有想過要測試這個 - 謝謝! – Radu 2010-08-26 22:02:37

3

我想你正在測量創建連接所花費的時間。要確認這一點,您可以將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

1

嘗試設置

reader.XmlResolver = null; 
+0

似乎沒有幫助,雖然我可能需要做很多迭代才能確定。 – Radu 2010-08-26 21:57:08

1

我比較了你的方法和另一個方法。只需下載數據並通過正則表達式查找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是更好:) 。