您的位置:首页 > 编程语言 > C#

C# read xml from a string and performance test

2008-02-07 19:40 441 查看
using System;

using System.Data;

using System.IO;

using System.Xml;

namespace ConsoleApplication1

{

class Class1

{

[STAThread]

static void Main(string[] args)

{

string xml = @"<?xml version='1.0'?><person firstname='bill' lastname='gates' />";

string s = string.Empty;

DateTime start = DateTime.Now;

TimeSpan ts;

for (int i = 0; i < 3000; ++i)

s = TestInnerXML(xml);

//around 900 milliseconds

ts = DateTime.Now - start;

Console.WriteLine("TestInnerXML elapsed time = " +

ts.Milliseconds.ToString());

start = DateTime.Now;

for (int i = 0; i < 3000; ++i)

s = TestXMLReader(xml);

//around 90-100 milliseconds (9 times faster.)

ts = DateTime.Now - start;

Console.WriteLine("TestXMLReader elapsed time = " +

ts.Milliseconds.ToString());

Console.WriteLine("Press Enter to Continue ...");

Console.ReadLine();

}

public static string TestInnerXML(string xmlString)

{

XmlDocument doc = new XmlDocument();

doc.InnerXml = xmlString;

XmlElement root = doc.DocumentElement;

return root.GetAttribute("firstname");

}

public static string TestXMLReader(string xmlString)

{

XmlTextReader reader = new XmlTextReader(xmlString, XmlNodeType.Document, null);

reader.MoveToContent();

string s = reader.GetAttribute("firstname");

reader.Close();

return s;

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: