天天看點

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();

                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)

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

                        i, false, "asdfgb", 123.456);

            Console.Read();

        }

}

最終結果整理:

方式:  linq  序列化  字元串

100:  28  104  11

1000:  32   108    41  

10000:  69  126  337

100000:  425  318   3341

随着次數的增加,估計反射的緩存還是很快的,序列化速度超過了linq to json,拼字元串從最快的變成最慢的

繼續閱讀