简单对比了一下MonoXml与SystemXml在Unity下的表现
测试代码
public class NewBehaviourScript : MonoBehaviour { // Use this for initialization void Start () { } static void TestXmlLoad(string xml) { SecurityParser parser = new SecurityParser(); parser.LoadXml(xml); } static void TestSystemXMLLoad(string xml) { XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); } int count = 0; // Update is called once per frame void Update () { if(++count == 200) { string xmlText = File.ReadAllText(@"F:\Projects\TestPXML\TestPXML\test.xml"); int LoadCount = 5; Stopwatch stopwatch = new Stopwatch(); { stopwatch.Start(); for (int i = 0; i < LoadCount; ++i) { TestXmlLoad(xmlText); } UnityEngine.Debug.Log(string.Format("MonoXml Load:{0}", stopwatch.Elapsed)); } { stopwatch.Stop(); stopwatch.Start(); for (int i = 0; i < LoadCount; ++i) { TestSystemXMLLoad(xmlText); } UnityEngine.Debug.Log(string.Format("SystemXml Load:{0}", stopwatch.Elapsed)); } } } }
测试用xml400kb左右。
时间:
看起来MonoXml会快一点,大约少1/3左右的时间开销。
内存:
开了DeepProfile。看起来Systemxml需要更少的内存,不开DeepProfile测不到内存,这就尴尬了。
另外在非Unity环境下测试了一下,使用代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using Mono.Xml; using System.Diagnostics; namespace TestPXML { class Program { private static List<object> Caches = new List<object>(); static void Main(string[] args) { // Console.WriteLine("prepare load from monoxml"); // Console.ReadKey(); string xmlText = Encoding.UTF8.GetString(Properties.Resources.SettlementForm); int LoadCount = 100; GC.Collect(); GC.Collect(); Stopwatch stopwatch = new Stopwatch(); // { // stopwatch.Start(); // // for(int i=0; i<LoadCount; ++i) // { // TestXmlLoad(xmlText); // } // // Console.WriteLine($"MonoXml Load:{stopwatch.Elapsed}"); // } Console.WriteLine("prepare load from system.xml"); Console.ReadKey(); { stopwatch.Stop(); stopwatch.Start(); for (int i = 0; i < LoadCount; ++i) { TestSystemXMLLoad(xmlText); } Console.WriteLine($"SystemXML Load:{stopwatch.Elapsed}"); } GC.Collect(); GC.Collect(); Console.WriteLine("all done, press any key."); Console.ReadKey(); } static void TestXmlLoad(string xml) { SecurityParser parser = new SecurityParser(); parser.LoadXml(xml); Caches.Add(parser); } static void TestSystemXMLLoad(string xml) { XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); Caches.Add(doc); } } }
为了避免误差,cache之类的,使用工具分两个波次测试。
SystemXML结论如下:
MonoXML结论如下:
因此基本可以证明,MonoXml加载速度比SystemXml快,但是需要的内存开销会高于System.xml