Linq 提供了一种在内存中操作数据的高效方式,写了一个测试 比较生成同等xml 的时间开销.
构建基础类 提供原始xml 操作 和 基于 linq 的xml 操作
using System; using System.IO; using System.Linq; using System.Reflection; using System.Xml; using System.Xml.Linq; namespace Common { public class LinqHelper { //Generates XML using XmlDocument public static void GenerateXmlUsingXmlDocument() { MemoryStream ms = new MemoryStream(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "no")); XmlElement assembliesNode = xmlDoc.CreateElement("Assemblies"); foreach (Type t in Assembly.GetAssembly(typeof(Object)).GetExportedTypes()) { XmlElement assemblyNode = xmlDoc.CreateElement("Assembly"); XmlAttribute fullTypeName = xmlDoc.CreateAttribute("FullTypeName"); fullTypeName.Value = t.ToString(); XmlAttribute isInterfaceName = xmlDoc.CreateAttribute("IsInterface"); isInterfaceName.Value = t.IsInterface.ToString(); assemblyNode.Attributes.Append(fullTypeName); assemblyNode.Attributes.Append(isInterfaceName); assembliesNode.AppendChild(assemblyNode); } xmlDoc.AppendChild(assembliesNode); xmlDoc.WriteContentTo(new XmlTextWriter(ms, System.Text.ASCIIEncoding.ASCII)); } //Generates XML using XElement public static void GenerateXmlUsingXElement() { MemoryStream ms = new MemoryStream(); XElement assembliesNode = new XElement("Assemblies", from Type t in Assembly.GetAssembly(typeof(Object)).GetExportedTypes() select new XElement("Assembly", new XAttribute("FullTypeName", t.ToString()), new XAttribute("IsInterface", t.IsInterface.ToString()))); assembliesNode.Save(new XmlTextWriter(ms, System.Text.ASCIIEncoding.ASCII)); } } }
调用主题
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Common; namespace XmlDocument_VS_XDocment { class Program { static void Main(string[] args) { Stopwatch sw = new Stopwatch(); for (int index = 0; index < 51; index++) { sw.Reset(); sw.Start(); LinqHelper.GenerateXmlUsingXmlDocument(); sw.Stop(); Console.Write("Generation time using XmlDocument " + "and XElement: " + sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); LinqHelper.GenerateXmlUsingXElement(); sw.Stop(); Console.WriteLine(" : " + sw.ElapsedMilliseconds); GC.Collect(); } Console.ReadKey(); } } }
控制台内执行结果
对比执行时间差异,结论已经很明确了.
时间: 2024-10-28 16:19:46