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();
}
时间: 2024-07-29 17:13:00

Json.NET Performance Tips的相关文章

Performance tips

HTML5 Techniques for Optimizing Mobile Performance Scrolling Performance

Solr performance tips

Page query result: Configure document cache: Configure query result cache: Configure filter cache: Startup or after commit warmup: Cache whole result pages (HTTP cache): Improve facet performance: Indexing time:

(一)Android性能优化系列---Performance Tips(文章出处:http://developer.android.com/training/articles/perf-tips.html#Myths)

本文列出的优化技巧主要是一些微小的性能提升,可能不会给你的程序性能改善产生显著的效果.决定程序整体性能的仍然取决于程序的业务逻辑设计.代码的数据结构和算法,这超出了本文的范围.你需要将这些优化技巧应用到平时的编码过程中,积少成多,也会对性能有很大的影响. 下面是写高效代码的两个基本原则: 1.不要写不需要的代码: 2.不要分配不必要的内存. android应用程序优化一个非常棘手的问题就是android硬件差异很大.不同的虚拟机.不同的SDK版本.app在不同的设备环境上运行速度和性能自然不同:

Android性能优化之Performance Tips

如果你真的愿意去努力,你人生最坏的结果,也不过是大器晚成. 原文链接:http://developer.android.com/training/articles/perf-tips.html#UseFinal 概述 这篇文档主要包含一些微小的最佳优化,当把这些组合起来的时候,可以提高App的整体性能,但它不太可能对性能造成戏剧性的影响.选择合适的算法和数据结构应该是你优先考虑的内容,但超出了本文的范围.这个文档更适合作为通用的编码技巧,通过这些技巧使我们的代码更高效. 编写高效代码有两个基本规

C#中,Json的序列化和反序列化的几种方式总结

什么是JSON? JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and easy for machines to parse and generate. JSON is a text format that is completely language independent. 翻译:Json[javascrip

腾讯云数据库团队:MySQL5.7 JSON实现简介

作者介绍:吴双桥 腾讯云工程师 阅读原文,更多技术干货,请访问腾云阁. 本文主要介绍在MySQL 5.7.7开始引入的非结构化数据类型JSON的特性以及具体的实现方式(包括存储方式).首先介绍为什么要引入JSON的原生数据类型的支持:接着介绍MySQL给用户提供的JSON操作函数,以及JSON路径表达式语法,结合两者,用户可以在数据库级别操作JSON的任意键值和数据:之后,重点介绍JSON在服务器侧的存储结构,这也是深入理解很多其他JSON特性的根基:在最后介绍JSON作为新数据类型的比较与排序

根据json对象的某一属性对其进行排序

compare(property) { return function(a, b) { var value1 = a[property]; var value2 = b[property]; return value1 - value2; } }, 排序前的json对象 <script> var json1 = [ {"name":"小明","avg":"80"}, {"name":"

ajax小demo-----ajax中json的使用

使用简单例子,表单的的输入,将表单输入以JSON的形式传入,并后台返回JSON格式,使用js函数处理,进行显示,进一步熟悉了ajax的用法,以及JSON的的使用.例子如下: html部分: <form action="test1.php" method="get" onsubmit="return check();">  <label for="username">用户名 </label>&

腾讯云数据库团队:MySQL5.7 JSON实现简单介绍

作者介绍:吴双桥 腾讯云project师 阅读原文.很多其它技术干货.请訪问fromSource=gwzcw.57435.57435.57435">腾云阁. 本文主要介绍在MySQL 5.7.7開始引入的非结构化数据类型JSON的特性以及详细的实现方式(包含存储方式).首先介绍为什么要引入JSON的原生数据类型的支持:接着介绍MySQL给用户提供的JSON操作函数,以及JSON路径表达式语法.结合两者,用户能够在数据库级别操作JSON的随意键值和数据:之后.重点介绍JSON在server側