zoukankan      html  css  js  c++  java
  • Json.NET Performance Tips

    原文: http://www.newtonsoft.com/json/help/html/Performance.htm

    To keep an application consistently fast, it is important to minimize the amount of time the .NET framework spends performing garbage collection. Allocating too many objects or allocating very large objects can slow down or even halt an application while garbage collection is in progress.

    To minimize memory usage and the number of objects allocated, Json.NET supports serializing and deserializing directly to a stream. Reading or writing JSON a piece at a time, instead of having the entire JSON string loaded into memory, is especially important when working with JSON documents greater than 85kb in size to avoid the JSON string ending up in the large object heap.

    HttpClient client = new HttpClient();
    
    // read the json into a string
    // string could potentially be very large and cause memory problems
    string json = client.GetStringAsync("http://www.test.co/large.json").Result;
    
    Person p = JsonConvert.DeserializeObject<Person>(json);
    HttpClient client = new HttpClient();
     
     using (Stream s = client.GetStreamAsync("http://www.test.com/large.json").Result)
    using (StreamReader sr = new StreamReader(s))
    using (JsonReader reader = new JsonTextReader(sr))
    {
        JsonSerializer serializer = new JsonSerializer();
    
        // read the json from a stream
        // json size doesn't matter because only a small piece is read at a time from the HTTP request
        Person p = serializer.Deserialize<Person>(reader);
    }

    Passing a JsonConverter to SerializeObject or DeserializeObject provides a simple way to completely change how an object is serialized. There is, however, a small amount of overhead; the CanConvert method is called for every value to check whether serialization should be handled by that JsonConverter.

    There are a couple of ways to continue to use JsonConverters without any overhead. The simplest way is to specify the JsonConverter using the JsonConverterAttribute. This attribute tells the serializer to always use that converter when serializing and deserializing the type, without the check.

    [JsonConverter(typeof(PersonConverter))]
    public class Person
    {
          public Person()
          {
              Likes = new List<string>();
          }
          public string Name { get; set; }
          public IList<string> Likes { get; private set; }
    }

    If the class you want to convert isn't your own and you're unable to use an attribute, a JsonConverter can still be used by creating your own IContractResolver.

    public class ConverterContractResolver : DefaultContractResolver
     {
         public new static readonly ConverterContractResolver Instance = new ConverterContractResolver();
     
         protected override JsonContract CreateContract(Type objectType)
         {
             JsonContract contract = base.CreateContract(objectType);
     
             // this will only be called once and then cached
            if (objectType == typeof(DateTime) || objectType == typeof(DateTimeOffset))
                contract.Converter = new JavaScriptDateTimeConverter();
    
            return contract;
        }
    }

    The IContractResolver in the example above will set all DateTimes to use the JavaScriptDateConverter.

    手动序列化

    The absolute fastest way to read and write JSON is to use JsonTextReader/JsonTextWriter directly to manually serialize types. Using a reader or writer directly skips any of the overhead from a serializer, such as reflection.

    public static string ToJson(this Person p)
    {
        StringWriter sw = new StringWriter();
        JsonTextWriter writer = new JsonTextWriter(sw);
    
        // {
        writer.WriteStartObject();
    
        // "name" : "Jerry"
        writer.WritePropertyName("name");
        writer.WriteValue(p.Name);
    
        // "likes": ["Comedy", "Superman"]
        writer.WritePropertyName("likes");
        writer.WriteStartArray();
        foreach (string like in p.Likes)
        {
            writer.WriteValue(like);
        }
        writer.WriteEndArray();
    
        // }
        writer.WriteEndObject();
    
        return sw.ToString();
    }
  • 相关阅读:
    第一个MIPS汇编
    选你所爱,爱你所选
    海明码(汉明码)的工作机制
    第一个x86汇编程序
    机器学习 coursera【week1-3】
    描述符应用与类的装饰器
    多态,封装,反射,类内置attr属性,os操作复习
    面向对象操作
    类属性的增删改查,类属性和实例属性
    os常用模块,json,pickle,shelve模块,正则表达式(实现运算符分离),logging模块,配置模块,路径叠加,哈希算法
  • 原文地址:https://www.cnblogs.com/ly7454/p/4681822.html
Copyright © 2011-2022 走看看