ServiceStack.Text 更快的序列化
Json.net 是以前最经常用的序列化组件,后来又注意到ServiceStack号称最快的,所以我做了以下测试
1)Json.net
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | <br> 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; } }<br><br>由上图对比可知,在序列化时 serviceStack.Text 比 Json.net 快5倍左右<br><br><br>下面再测试反序列化<br><br><br> |
但是有一个很致命的缺陷,serviceStack.Text在处理 复杂类就显示很不方便了
如
1 2 3 4 5 6 7 8 9 10 11 12 13 | [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是不会被正确序列化的
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步