原文: 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();
}

Json.NET Performance Tips的更多相关文章

  1. Android 性能优化(19)*代码优化11条技巧:Performance Tips

    Performance Tips 1.In this document Avoid Creating Unnecessary Objects 避免多余的对象 Prefer Static Over Vi ...

  2. SQL Server performance tips

    Refer to: http://harriyott.com/2006/01/sql-server-performance-tips A colleague of mine has been look ...

  3. Performance tips

    HTML5 Techniques for Optimizing Mobile Performance Scrolling Performance layout-performance

  4. 翻译--Blazing fast node.js: 10 performance tips from LinkedIn Mobile

    1.避免使用同步代码: // Good: write files asynchronously fs.writeFile('message.txt', 'Hello Node', function ( ...

  5. [Javascript]3. Improve you speed! Performance Tips

    /** Let inheritance help with memory efficiency */ function SignalFire(ID, startingLogs){ this.fireI ...

  6. [Angular] Some performance tips

    The talk from here. 1. The lifecycle in Angular component: constructor vs ngOnInit: Constructor: onl ...

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

    在这篇文章中,我们将会学到如何使用C#,来序列化对象成为Json格式的数据,以及如何反序列化Json数据到对象. 什么是JSON? JSON (JavaScript Object Notation) ...

  8. Visual Studio 2013下JSON可视化工具

          Visual Studio 2013现在我们有个小工具可以实现JSON可视化,这样给我们调试JSON提供了便利. JSON这种数据格式已经比较流行,在WEB前端随处可见. 在你需要安装VS ...

  9. MySQL5.7 JSON实现简介

    版权声明:本文由吴双桥原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/205 来源:腾云阁 https://www.qclo ...

随机推荐

  1. NOI-OJ 2.2 ID:1696 逆波兰表达式

    思路 很容易看出规律,一个运算符出现,其后就一定需要左值和右值,而左值和右值有可能还是运算符,这就需要继续递归.递归终止的条件就是遇到数字. 逆波兰表达式其实是构造成了一颗二叉树 例程 #includ ...

  2. [物理学与PDEs]第4章习题4 一维理想反应流体力学方程组的守恒律形式及其 R.H. 条件

    写出在忽略粘性与热传导性, 即设 $\mu=\mu'=\kappa=0$ 的情况, 在 Euler 坐标系下具守恒律形式的一维反应流动力学方程组. 由此求出在解的强间断线上应满足的 R.H. 条件 ( ...

  3. selenium新手常遇到的坑

    本文是以Chrome为例: 1.Chrome相对应的chromedriver的版本信息[点击浏览器的右上角的浏览器信息--------帮助-------关于Google Chrome查看相对应的信息- ...

  4. Arduino传感器学习目录

    Arduino-接口图  在Windows上安装Arduino-IDE  函数库和程序架构介绍   Arduino语法-变量和常量 Arduino常用的数据类型以及转换  Arduino—运算符   ...

  5. 大家都知道fastclick能解决300ms延迟,现在我们来看一下,使用方法

    1.在终端输入以下命令进行安装 npm install fastclick -S 2.在你用脚手架搭建好的项目中,找到mian.js这个入口文件,打开 3.在其中加入: import FastClic ...

  6. day 17 - 1 递归函数

    递归函数 什么是递归 了解什么是递归 : 在函数中调用自身函数 最大递归深度默认是 997/998 —— 是 python 从内存角度出发做得限制 能看懂递归 能知道递归的应用场景 初识递归 —— 二 ...

  7. 51nod 1215 数组的宽度

    若一个数在一段区间内作为最大值存在,那么答案应该加上这个数 若一个数在一段区间内作为最小值存在,那么答案应该减去这个数 所以我们利用单调栈,高效求出a[i]在哪个区间内作为最大/最小值存在,从而确定, ...

  8. error: no matching function for call to 'std::exception:exception(const char[16])'

    环境:codeblocks 语言:C++ 在执行:throw new exception("queue is empty.");时 遇到问题:error: no matching ...

  9. maven 一些整理

    1.发布jar包到私服,需要进入项目目录 发布jar   :mvn deploy 发布源码 :mvn source:jar deploy,这个需要依赖一个maven插件: <plugin> ...

  10. TP5报错

    Array to string conversion 数组不能用echo来输出,可使用var_dump().dump()或print_r()