ServiceStack.Text 更快的序列化

Json.net 是以前最经常用的序列化组件,后来又注意到ServiceStack号称最快的,所以我做了以下测试

1)Json.net

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace Json.net
{
    class Program
    {
       static void Main(string[] args)
        {
            Order order = new Order()
            {
                CltAddr = "aaa",
                CltName = "Aven",
                CltPhone = "0345-3423434"
            };  
            order.OrderId = "001";
            
            Stopwatch sw=new Stopwatch();
            sw.Reset();
            sw.Start();
            for (int i = 0; i < 1000*1000; i++)
            {
                order.OrderId = i.ToString();
                string json = order.ToJson();
            }
            sw.Stop();
            Console.WriteLine("Json.net消耗时间:{0}ms",sw.ElapsedMilliseconds);
            Console.Read();
        
        }
    }

    public static class JsonHelper
    {
        public static String ToJson<T>(this T ojb) where T : class
        {
            return JsonConvert.SerializeObject(ojb, Formatting.Indented);

        }
        public static T ToInstance<T>(this String jsonStr) where T : class
        {
            var instance = JsonConvert.DeserializeObject<T>(jsonStr);

            return instance;

        }
    }

    class Order
    {
        public string OrderId { get; set; }
        public string CltName;
        public string CltPhone;
        public string CltAddr;
    }

   
}

  

 

  

 

2)ServiceStack.Text

 


using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using ServiceStack; namespace ServiceStace.Text { class Program { static void Main(string[] args) { Order order=new Order(); order.OrderId = "001"; order.CltInfo=new CltInfo() { CltAddr ="aaa", CltName="Aven", CltPhone = "0345-3423434" }; Stopwatch sw=new Stopwatch(); sw.Reset(); sw.Start(); for (int i = 0; i < 1000*1000; i++) { order.OrderId = i.ToString(); string json = order.ToJson(); } sw.Stop(); Console.WriteLine("ServiceStack.Text消耗时间:{0}ms",sw.ElapsedMilliseconds); Console.Read(); } } class Order { public string OrderId { get; set; } public CltInfo CltInfo { get; set; } } class CltInfo { public string CltName; public string CltPhone; public string CltAddr; } }

 

由上图对比可知,在序列化时 serviceStack.Text 比 Json.net 快5倍左右


下面再测试反序列化


  

 但是有一个很致命的缺陷,serviceStack.Text在处理 复杂类就显示很不方便了

[Serializable]
    public class Order
    {
        public string OrderId { get; set; }
        public ClientInfo CltInfo { get; set; }
    }
    [Serializable] 
   public class ClientInfo
    {
        public string CltName;
        public string CltPhone;
        public string CltAddr;
    }

  

要序列化 Order 的话,结果只是 一个OrderId:"123223",CltInfo:"" 

cltInfo是不会被正确序列化的

posted @ 2016-07-13 21:23  zslm___  阅读(324)  评论(0编辑  收藏  举报