<FormContext Id=""6E03A8E3614C4946825D8705CF24A472"">
<SameDept>Y</SameDept>
<AppMgr>0023456</AppMgr>
<CPWin>0045387</CPWin>
<PTMan>0012083</PTMan>
<ptApplyDate>2006/11/16</ptApplyDate>
<ptApplyerName>王建民</ptApplyerName>
.... 省略 ....
<ptInDate>2006/11/17</ptInDate>
<ptAcctOut>0000000</ptAcctOut>
<ptDeptOut></ptDeptOut>
<ptAcctIn>0000000</ptAcctIn>
<ptDeptIn></ptDeptIn>
</FormContext>
string x= @"
<FormContext Id=""6E03A8E3614C4946825D8705CF24A472"">
<SameDept>Y</SameDept>
<AppMgr>0011456</AppMgr>
...略...
<ptDeptIn></ptDeptIn>
</FormContext>
";
int totalCount = 50000;
for (int testMode = 1; testMode <= 3; testMode++)
{
Response.Write("<hr><b>");
if (testMode == 1) Response.Write("XmlDocument");
if (testMode == 2) Response.Write("XmlPathNavigator");
if (testMode == 3) Response.Write("RegularExpression");
Response.Write("</b>");
Response.Write("<br>Total Count=" + totalCount);
DateTime st = DateTime.Now;
Hashtable ht = new Hashtable();
for (int i = 0; i < totalCount; i++)
{
ht.Clear();
switch (testMode)
{
case 1: //XmlDocument
XmlDocument xd = new XmlDocument();
xd.LoadXml(x);
foreach (XmlNode n in xd.DocumentElement.ChildNodes)
ht.Add(n.Name, n.InnerText);
break;
case 2: //XmlNavigator
XmlTextReader xtr = new XmlTextReader(new StringReader(x));
XPathDocument xpd = new XPathDocument(xtr);
XPathNavigator xpn = xpd.CreateNavigator();
xpn.MoveToFirstChild();
XPathNodeIterator xpni = xpn.SelectChildren(XPathNodeType.Element);
while (xpni.MoveNext())
ht.Add(xpni.Current.Name, xpni.Current.Value);
break;
case 3: //Regular Expression
foreach (Match m in Regex.Matches(x.Substring(1), "(?ims)<(?<tagName>.+?)>(?<text>.*?)</.+?>"))
ht.Add(m.Groups["tagName"].Value, m.Groups["text"].Value);
break;
}
}
Response.Write("<br>Get Nodes Count=" + ht.Count);
TimeSpan ts = DateTime.Now - st;
Response.Write("<br>Duration=" + ts.Seconds + "." + ts.Milliseconds);
}
以上的測試方法是用XmlDocument/XmlXPathNavigator/RegularExpression三種方式取出22個ChildNode的資料,存入Hashtable,反覆跑50,000次,並記錄執行時間(Duration單位為秒)。結果讓我大吃一驚!
啥?? XmlDocument比XmlXPathNavigator還快,而RegularExpression慢了近三倍! 難道我被騙了這麼多年??? 忽然想到曾經讀過文章說.NET 2.0對XmlDocument做了改善,於是將同樣的程式搬到1.1上再跑一次:
不過,大家要留意,在我的測試中,XML並不大,而且已經以字串形式存在。如果是巨大而複雜的XML檔,結果可能會有差異! 至少,在我這次的應用中,應該可以安心地使用XmlDocument Parse XML,不必擔心遭天讉。