Newtonsoft.json中 linq to json 和序列化哪个快?

Newtonsoft.json是最常用的json序列化组件,当然他不是最快的,但是是功能最全的。。

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Diagnostics;

using Newtonsoft.Json.Linq;

using Newtonsoft.Json;

 

namespace ConsoleApplication2

{

    public class Entity

    {

        public int a;

        public bool b = false;

        public string s = "asdfgb";

        public double d = 123.456;

    }

 

    class Program

    {

        static void Main(string[] args)

        {

 

            Stopwatch w = new Stopwatch();

            w.Start();

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

            {

                Entity a = new Entity();

                a.a = i;

                string result = new JObject(new JProperty("a", i),

                    new JProperty("b", a.b),

                    new JProperty("s", a.s),

                     new JProperty("d", a.d)

                    ).ToString();

            }

 

 

            w.Stop();

            Console.WriteLine(w.ElapsedMilliseconds);

 

 

            w.Reset();

            w.Start();

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

            {

                try

                {

                    //Entity a = new Entity();

                    //a.a = i;

                    string result = JsonConvert.SerializeObject(new

                    {

                        a = i,

                        b = false,

                        s = "asdfgb",

                        d = 123.456

 

                    });

                }

                catch (Exception e)

                {

 

                }

 

            }

 

            w.Stop();

            Console.WriteLine(w.ElapsedMilliseconds);

 

            w.Reset();

            w.Start();

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

            {

                try

                {

                    //Entity a = new Entity();

                    //a.a = i;

                    string result = string.Format("{a: {0},b:{1},s:{2}},d:{3}",

                        i, false, "asdfgb", 123.456);

                }

                catch (Exception e)

                {

 

                }

 

            }

 

            w.Stop();

            Console.WriteLine(w.ElapsedMilliseconds);

 

            Console.Read();

        }

    }

}

 

最终结果整理:

方式:  linq  序列化  字符串

100:  28  104  11

1000:  32   108    41  

10000:  69  126  337

100000:  425  318   3341

随着次数的增加,估计反射的缓存还是很快的,序列化速度超过了linq to json,拼字符串从最快的变成最慢的

posted @ 2014-01-31 23:15  咖喱gg  阅读(941)  评论(1编辑  收藏  举报