using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using System.Diagnostics;
using System.Xml.XPath;
using System.Xml;
namespace TestXmlPerformance
{ class Program
{ static void GenSampleXml()
{ StringBuilder sb = new StringBuilder();
sb.Append("<root>"); Random rnd = new Random();
for (int i = 0; i < 20000; i++)
{ sb.AppendFormat("<pack id=\"{0}\">", i); for (int j = 0; j < 100; j++)
sb.AppendFormat("<item model=\"{0}\" />", rnd.Next(20));
sb.Append("</pack>"); }
sb.Append("</root>"); File.WriteAllText(".\\Sample.xml", sb.ToString()); }
static void Main(string[] args)
{ //GenSampleXml();
{ Stopwatch sw = new Stopwatch();
sw.Start();
XDocument xd = XDocument.Load(".\\Sample.xml"); var q = from o in xd.Descendants("item") where o.Attribute("model").Value == "7" select o;
Console.WriteLine(q.Count());
sw.Stop();
Console.WriteLine("Test 1: {0}ms", sw.ElapsedMilliseconds);
}
{ Stopwatch sw = new Stopwatch();
sw.Start();
XDocument xd = XDocument.Load(".\\Sample.xml"); Console.WriteLine(
xd.XPathSelectElements("root/pack/item[@model='7']") .Count()
);
sw.Stop();
Console.WriteLine("Test 2: {0}ms", sw.ElapsedMilliseconds);
}
{ Stopwatch sw = new Stopwatch();
sw.Start();
XmlDocument xd = new XmlDocument();
xd.Load(".\\Sample.xml"); Console.WriteLine(
xd.DocumentElement
.SelectNodes("pack/item[@model='7']").Count );
sw.Stop();
Console.WriteLine("Test 3: {0}ms", sw.ElapsedMilliseconds);
}
Console.Read();
}
}
}