DataContractSerializer vs XmlSerializer vs DataContractJsonSerializer vs SoapFormatter vs BinaryFormatter 性能测试对比


namespace Test
{
    using System;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Json;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;
    using Microshaoft;
    using Test.Share;
    public class Class1
    {
        static WebDirectory _wd = null;
        static void Main(string[] args)
        {
            WebDirectory x = new WebDirectory();
            x.Name = "Microshaoft";
            DateTime now = DateTime.Now;
            WebFile y1 = new WebFile();
            y1.Name = "Microshaoft简体繁體中文";
            y1.IsReadOnly = false;
            y1.Url = "http://www.microshaoft.com";
            y1.CreateTime = now;
            y1.LastWriteTime = now;
            WebDirectory x1 = new WebDirectory();
            x1.Name = "Sub1";
            //y1.Directory = x; //循环引用
            WebFile y2 = new WebFile();
            y2.Name = "Microshaoft中文";
            y2.Flag = FlagEnum.Value2;
            y2.CreateTime = now;
            y2.LastWriteTime = now;
            WebFile[] a = new WebFile[2];
            a[0] = y1;
            a[1] = y2;
            x.WebFiles = a;
            _wd = x;
            int iteration = 10000;
            Type t = _wd.GetType();
            int length = 0;
            XmlSerializer serializer1 = new XmlSerializer(t);
            CodeTimer.ParallelTime
                        (
                            "TestXmlSerializer"
                            , iteration
                            , () =>
                            {
                                length = TestXmlSerializerOnce(serializer1);
                            }
                        );
            Console.WriteLine("Length: {0}", length);
            DataContractSerializer serializer2 = new DataContractSerializer(t);
            CodeTimer.ParallelTime
                        (
                            "TestDataContractSerializer"
                            , iteration
                            , () =>
                            {
                                length = TestDataContractSerializerOnce(serializer2);
                            }
                        );
            Console.WriteLine("Length: {0}", length);
            DataContractJsonSerializer serializer3 = new DataContractJsonSerializer(t);
            CodeTimer.ParallelTime
                        (
                            "TestDataContractJsonSerializer"
                            , iteration
                            , () =>
                            {
                                length = TestDataContractJsonSerializerOnce(serializer3);
                            }
                        );
            Console.WriteLine("Length: {0}", length);
            CodeTimer.ParallelTime
                        (
                            "TestSoapFormatter"
                            , iteration
                            , () =>
                            {
                                length = TestSoapFormatterOnce();
                            }
                        );
            Console.WriteLine("Length: {0}", length);
            CodeTimer.ParallelTime
                        (
                            "TestBinaryFormatter"
                            , iteration
                            , () =>
                            {
                                length = TestBinaryFormatterOnce();
                            }
                        );
            Console.WriteLine("Length: {0}", length);
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Hello World");
            Console.WriteLine(Environment.Version.ToString());
            Console.ReadLine();
        }
        static int TestXmlSerializerOnce(XmlSerializer serializer)
        {
            string xml = string.Empty;
            xml = SerializerHelper.XmlSerializerObjectToXml<WebDirectory>
                                            (
                                                _wd
                                                , serializer
                                                , new XmlWriterSettings()
                                                    {
                                                        // = true
                                                        OmitXmlDeclaration = true
                                                        , Encoding= Encoding.UTF8
                                                    }
                                            );
            //Console.WriteLine(xml.Length);
            WebDirectory wd = SerializerHelper.XmlSerializerXmlToObject<WebDirectory>(xml, serializer);
            return xml.Length;
        }
        static int TestDataContractSerializerOnce(DataContractSerializer serializer)
        {
            string xml = string.Empty;
            xml = SerializerHelper.DataContractSerializerObjectToXml<WebDirectory>(_wd, serializer);
            //Console.WriteLine(xml.Length);
            WebDirectory wd = SerializerHelper.DataContractSerializerXmlToObject<WebDirectory>(xml, serializer);
            return xml.Length;
        }
        static int TestDataContractJsonSerializerOnce(DataContractJsonSerializer serializer)
        {
            string json = string.Empty;
            json = SerializerHelper.DataContractSerializerObjectToJson<WebDirectory>(_wd, serializer);
            //Console.WriteLine(xml.Length);
            WebDirectory wd = SerializerHelper.DataContractSerializerJsonToObject<WebDirectory>(json, serializer);
            return json.Length;
        }
        static int TestSoapFormatterOnce()
        {
            string soap = string.Empty;
            soap = SerializerHelper.FormatterObjectToSoap<WebDirectory>(_wd);
            //Console.WriteLine(xml.Length);
            WebDirectory wd = SerializerHelper.FormatterSoapToObject<WebDirectory>(soap);
            return soap.Length;
        }
        static int TestBinaryFormatterOnce()
        {
            byte[] buffer;
            //xml = SerializerHelper.XmlSerializerObjectToXml<WebDirectory>(_wd, Encoding.UTF8);
            //WebDirectory wd = SerializerHelper.XmlSerializerXmlToObject<WebDirectory>(xml);
            buffer = SerializerHelper.FormatterObjectToBinary<WebDirectory>(_wd);
            //Console.WriteLine(xml.Length);
            WebDirectory wd = SerializerHelper.FormatterBinaryToObject<WebDirectory>(buffer);
            return buffer.Length;
        }
    }
}
namespace Microshaoft
{
    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    using System.Threading;
    using System.Threading.Tasks;
    public static class CodeTimer
    {
        public static void Initialize()
        {
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
            Thread.CurrentThread.Priority = ThreadPriority.Highest;
            Time("", 1, () => { });
        }
        public static void ParallelTime(string name, int iteration, Action action)
        {
            InternalIterationProcess
                     (
                        name
                        , iteration
                        , () =>
                        {
                            Parallel.For
                                    (
                                        0
                                        , iteration
                                        , new ParallelOptions()
                                        {
                                            MaxDegreeOfParallelism = 1
                                            //, TaskScheduler = null
                                        }
                                                , i =>
                                                {
                                                    action();
                                                }
                                    );
                        }
                    );
        }
        private static void InternalIterationProcess(string name, int iteration, Action action)
        {
            if (string.IsNullOrEmpty(name))
            {
                return;
            }
            // 1.
            ConsoleColor currentForeColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine(name);
            // 2.
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
            int[] gcCounts = new int[GC.MaxGeneration + 1];
            for (int i = 0; i <= GC.MaxGeneration; i++)
            {
                gcCounts[i] = GC.CollectionCount(i);
            }
            // 3.
            Stopwatch watch = new Stopwatch();
            watch.Start();
            ulong cycleCount = GetCycleCount();
            action();
            ulong cpuCycles = GetCycleCount() - cycleCount;
            watch.Stop();
            // 4.
            Console.ForegroundColor = currentForeColor;
            Console.WriteLine
                            (
                                "{0}Time Elapsed:{0}{1}ms"
                                , "\t"
                                , watch.ElapsedMilliseconds.ToString("N0")
                            );
            Console.WriteLine
                            (
                                "{0}CPU Cycles:{0}{1}"
                                , "\t"
                                , cpuCycles.ToString("N0")
                            );
            // 5.
            for (int i = 0; i <= GC.MaxGeneration; i++)
            {
                int count = GC.CollectionCount(i) - gcCounts[i];
                Console.WriteLine
                            (
                                "{0}Gen {1}: {0}{0}{2}"
                                , "\t"
                                , i
                                , count
                            );
            }
            Console.WriteLine();
        }
        public static void Time(string name, int iteration, Action action)
        {
            InternalIterationProcess
                                (
                                    name
                                    , iteration
                                    , () =>
                                    {
                                        for (int i = 0; i < iteration; i++)
                                        {
                                            action();
                                        }
                                    }
                                );
        }
        private static ulong GetCycleCount()
        {
            ulong cycleCount = 0;
            QueryThreadCycleTime(GetCurrentThread(), ref cycleCount);
            return cycleCount;
        }
        [DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool QueryThreadCycleTime(IntPtr threadHandle, ref ulong cycleTime);
        [DllImport("kernel32.dll")]
        static extern IntPtr GetCurrentThread();
    }
}
namespace Test.Share
{
    using System;
    using System.Runtime.Serialization;
    using System.Xml.Serialization;
    [XmlRoot("WebDirectory")]
    [Serializable]
    [DataContract]
    public class WebDirectory
    {
        [XmlAttribute("Name")]
        [DataMember]
        public string Name;
        [XmlArrayItem("WebFile", typeof(WebFile))]
        [XmlArray("WebFiles")]
        [DataMember]
        public WebFile[] WebFiles;
    }
    [DataContract]
    public enum FlagEnum : uint
    {
        [EnumMember]
        Value1
        ,
        [EnumMember]
        Value2
    }
    [Serializable]
    [DataContract]
    public class WebFile
    {
        [XmlAttribute("Name")]
        [DataMember]
        public string Name;
        [XmlAttribute("CreateTime")]
        [DataMember]
        public DateTime CreateTime;
        [XmlAttribute("LastWriteTime")]
        [XmlIgnore()]
        [DataMember]
        public DateTime LastWriteTime;
        [XmlAttribute("Length")]
        [DataMember]
        public long Length;
        //[XmlAttribute("Url")]
        [XmlElement("Url")]
        [DataMember]
        public string Url;
        [XmlAttribute("IsReadOnly")]
        [DataMember]
        public bool IsReadOnly;
        [XmlAttribute("Flag")]
        [DataMember]
        public FlagEnum Flag;
        [XmlElement("Directory")]
        [DataMember]
        public WebDirectory Directory;
    }
}
namespace Microshaoft
{
    using System.IO;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Runtime.Serialization.Formatters.Soap;
    using System.Runtime.Serialization.Json;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;
    public static class SerializerHelper
    {
        public static T XmlSerializerXmlToObject<T>(string xml, XmlSerializer serializer = null)
        {
            StringReader stringReader = new StringReader(xml);
            XmlReader xmlReader = XmlReader.Create(stringReader);
            if (serializer == null)
            {
                serializer = new XmlSerializer(typeof(T));
            }
            return (T) serializer.Deserialize(xmlReader);
        }
        public static string XmlSerializerObjectToXml<T>(T target, XmlSerializer serializer = null, XmlWriterSettings settings = null)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                using (XmlWriter writer = XmlTextWriter.Create(stream, settings))
                {
                    if (serializer == null)
                    {
                        serializer = new XmlSerializer(typeof(T));
                    }
                    serializer.Serialize(writer, target);
                    byte[] buffer = StreamDataHelper.ReadDataToBytes(stream);
                    if (settings == null)
                    {
                        settings = writer.Settings;
                    }
                    var e = settings.Encoding;
                    var p = e.GetPreamble().Length;
                    string s = e.GetString(buffer, p, buffer.Length - p);
                    writer.Close();
                    return s;
                }
            }
        }
        public static string DataContractSerializerObjectToXml<T>(T target, DataContractSerializer serializer)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, target);
                byte[] buffer = StreamDataHelper.ReadDataToBytes(ms);
                string xml = Encoding.UTF8.GetString(buffer);
                ms.Close();
                return xml;
            }
        }
        public static string DataContractSerializerObjectToXml<T>(T target)
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            string xml = DataContractSerializerObjectToXml<T>(target, serializer);
            return xml;
        }
        public static T DataContractSerializerXmlToObject<T>(string xml, DataContractSerializer serializer)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(xml);
            using (MemoryStream ms = new MemoryStream(buffer))
            {
                T target = (T) serializer.ReadObject(ms);
                ms.Close();
                return target;
            }
        }
        public static T DataContractSerializerXmlToObject<T>(string xml)
        {
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            byte[] buffer = Encoding.UTF8.GetBytes(xml);
            using (MemoryStream ms = new MemoryStream(buffer))
            {
                T target = (T) serializer.ReadObject(ms);
                ms.Close();
                return target;
            }
        }
        public static string FormatterObjectToSoap<T>(T target)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                SoapFormatter formatter = new SoapFormatter();
                formatter.Serialize(stream, target);
                string soap = Encoding.UTF8.GetString(stream.GetBuffer());
                return soap;
            }
        }
        public static T FormatterSoapToObject<T>
                                    (
                                        string soap
                                    )
        {
            using (MemoryStream stream = new MemoryStream())
            {
                SoapFormatter formater = new SoapFormatter();
                byte[] data = Encoding.UTF8.GetBytes(soap);
                stream.Write(data, 0, data.Length);
                stream.Position = 0;
                T target = (T) formater.Deserialize(stream);
                return target;
            }
        }
        public static byte[] FormatterObjectToBinary<T>
                                    (
                                        T target
                                    )
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formater = new BinaryFormatter();
                formater.Serialize(stream, target);
                byte[] buffer = stream.ToArray();
                return buffer;
            }
        }
        public static T FormatterBinaryToObject<T>
                                    (
                                        byte[] data
                                    )
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formater = new BinaryFormatter();
                stream.Write(data, 0, data.Length);
                stream.Position = 0;
                T target = (T) formater.Deserialize(stream);
                return target;
            }
        }
        public static string DataContractSerializerObjectToJson<T>(T target)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            string json = DataContractSerializerObjectToJson<T>(target);
            return json;
        }
        public static string DataContractSerializerObjectToJson<T>(T target, DataContractJsonSerializer serializer)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, target);
                string json = Encoding.UTF8.GetString(ms.GetBuffer());
                ms.Close();
                return json;
            }
        }
        public static T DataContractSerializerJsonToObject<T>(string json)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            T target = DataContractSerializerJsonToObject<T>(json, serializer);
            return target;
        }
        public static T DataContractSerializerJsonToObject<T>(string json, DataContractJsonSerializer serializer)
        {
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
            T target = (T) serializer.ReadObject(ms);
            ms.Close();
            ms.Dispose();
            ms = null;
            return target;
        }
    }
}
namespace Microshaoft
{
    using System.IO;
    public static class StreamDataHelper
    {
        public static byte[] ReadDataToBytes(Stream stream)
        {
            byte[] buffer = new byte[64 * 1024];
            MemoryStream ms = new MemoryStream();
            int r = 0;
            int l = 0;
            long position = -1;
            if (stream.CanSeek)
            {
                position = stream.Position;
                stream.Position = 0;
            }
            while (true)
            {
                r = stream.Read(buffer, 0, buffer.Length);
                if (r > 0)
                {
                    l += r;
                    ms.Write(buffer, 0, r);
                }
                else
                {
                    break;
                }
            }
            byte[] bytes = new byte[l];
            ms.Position = 0;
            ms.Read(bytes, 0, (int)l);
            ms.Close();
            ms.Dispose();
            ms = null;
            if (position >= 0)
            {
                stream.Position = position;
            }
            return bytes;
        }
    }
}

posted @ 2012-04-06 23:24  于斯人也  阅读(1041)  评论(0编辑  收藏  举报