.net performance optimization of --- ServiceStack.Text instead of Newtonsoft.Json

Test code (Nuget introduced Newtonsoft.Json and ServiceStack.Text two dll)

    public class People
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Sex { get; set; }
        public string Phone { get; set; }
        public int Height { get; set; }
        public int Weight { get; set; }
    }

    class Program
    {
        static void Main()
        {
            TimerDeserialize(50000);
            TimerDeserialize(100000);
            TimerDeserialize(500000);
            TimerDeserialize(1000000);
            Console.ReadKey();
        }

        private static void TimerSerialize(int count)
        {
            var people = new People { Id = "1", Name = "测试", Sex = "男", Phone = "1546789712", Height = 170, Weight = 120 };
            Stopwatch jsonWatch = new Stopwatch();
            jsonWatch.Start();
            for (int i = 0; i < count; i++)
            {
                var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(people);
            }
            jsonWatch.Stop();
            Console.WriteLine($"Newtonsoft.Json 序列化对象数量:{count},耗时:{jsonWatch.ElapsedMilliseconds} ms");

            Stopwatch stackWatch = new Stopwatch();
            stackWatch.Start();
            for (int i = 0; i < count; i++)
            {
                var jsonStr = ServiceStack.Text.JsonSerializer.SerializeToString(people);
            }
            
            stackWatch.Stop();
            Console.WriteLine($"ServiceStack.Text 序列化对象数量:{count},耗时:{stackWatch.ElapsedMilliseconds} ms");
        }

        private static void TimerDeserialize(int count)
        {
            var jsonStr = "{ \"Id\":\"1\",\"Name\":\"测试\",\"Sex\":\"男\",\"Phone\":\"1546789712\",\"Height\":170,\"Weight\":120,\"cars\":[{\"Color\":\"White\",\"Price\":483924028.00,\"BuyDate\":\"2019-04-03T13:31:36.1883973+08:00\"}]}";

            Stopwatch jsonWatch = new Stopwatch();
            jsonWatch.Start();
            for (int i = 0; i < count; i++)
            {
                var jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject<People>(jsonStr);
            }
            jsonWatch.Stop();
            Console.WriteLine($"Newtonsoft.Json 反序列化对象数量:{count},耗时:{jsonWatch.ElapsedMilliseconds} ms");
            Stopwatch stackWatch = new Stopwatch();
            stackWatch.Start();
            for (int i = 0; i < count; i++)
            {
                var stackOjbect = ServiceStack.Text.JsonSerializer.DeserializeFromString<People>(jsonStr);
            }
            stackWatch.Stop();
            Console.WriteLine($"ServiceStack.Text 反序列化对象数量:{count},耗时:{stackWatch.ElapsedMilliseconds} ms");
        }
    }

result:

In the case of large data, ServiceStack.Text deserialization of about twice Newtonsoft.Json. Serialization or less.

 

Now ServiceStack.Text a fee is better for open source, see the article written can have contact with quota restrictions, reproduced over

Original Address: http: //blog.csdn.net/hao_ds/article/details/73648130

ServiceStack start 4.0 has become a commercial product, is no longer completely free, open source is good news, the main function of the free quota limit LicenseUtils.cs file under ServiceStack.Text class library, simply add one line of code from GitHub After downloading the source code again compiler can remove the restriction, as follows:

Precautions:

When using a sequence into ServiceStack.Text json format, when the attribute of the time datetime, returns a new date (324234234) string, if you want to return yyyy-MM-dd HH: mm: ss format Date We need to modify the source code, add the following code in jsconfig.cs:

private static bool dMsDatetimeFormat=true;
 
      public static bool MsDatetimeFormat
      {
          get { return dMsDatetimeFormat; }
          set { dMsDatetimeFormat = value; }
      }

This is used to indicate whether the conversion of the kind just to see the custom format.

Then modify DateTimeSerializer.cs file public static void WriteWcfJsonDate (TextWriter writer, DateTime dateTime) Method

The modified code as follows

public static void WriteWcfJsonDate(TextWriter writer, DateTime dateTime)
    {
        if (JsConfig.AssumeUtc && dateTime.Kind == DateTimeKind.Unspecified)
        {
            dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
        }
 
        if (JsConfig.DateHandler == DateHandler.ISO8601)
        {
            writer.Write(dateTime.ToString("o", CultureInfo.InvariantCulture));
            return;
        }
 
        if (JsConfig.DateHandler == DateHandler.RFC1123)
        {
            writer.Write(dateTime.ToUniversalTime().ToString("R", CultureInfo.InvariantCulture));
            return;
        }
 
        var timestamp = dateTime.ToUnixTimeMs();
        string offset = null;
        if (dateTime.Kind != DateTimeKind.Utc)
        {
            if (JsConfig.DateHandler == DateHandler.TimestampOffset && dateTime.Kind == DateTimeKind.Unspecified)
                offset = UnspecifiedOffset;
            else
                offset = LocalTimeZone.GetUtcOffset(dateTime).ToTimeOffsetString();
        }
        else
        {
            // Normally the JsonDateHandler.TimestampOffset doesn't append an offset for Utc dates, but if
            // the JsConfig.AppendUtcOffset is set then we will
            if (JsConfig.DateHandler == DateHandler.TimestampOffset && JsConfig.AppendUtcOffset.HasValue && JsConfig.AppendUtcOffset.Value)
                offset = UtcOffset;
        }
 
        if (JsConfig.MsDatetimeFormat)
        {
            writer.Write(dateTime.ToString("yyyy-MM-dd hh:mm:ss"));
        }
        else
        {
 
            writer.Write(EscapedWcfJsonPrefix);
            writer.Write(timestamp);
            if (offset != null)
            {
                writer.Write(offset);
            }
            writer.Write(EscapedWcfJsonSuffix);
        }
 
 
    }

Such reuse when returned serialization method is '2015-09-08 11:11:11' format of the

When you do not use, want to restore the default mode, just before serialization using the phrase on the line

ServiceStack.Text.JsConfig.MsDatetimeFormat = false;

Original Address: http://blog.sina.com.cn/s/blog_53a04e6c0102wh6s.html

Published 37 original articles · won praise 3 · Views 6328

Guess you like

Origin blog.csdn.net/huan13479195089/article/details/88993539