原文: 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. Linux下 tftp 服务器的安装与使用

    安装步骤: 1. 安装xinetd, tftp-hpa tftpd-hpa a.  sudo apt-get install xinetd b.  sudo apt-get install tftp- ...

  2. C#获取根目录的方法总结

    1.控制台应用程序 static void Main(string[] args) { //1.Environment.CurrentDirectory Console.WriteLine(Envir ...

  3. 查看weblogic版本号

    通过WebLogic配置文件config.xml,示例如下: # cat config.xml|grep version

  4. H5_0001:localStorage本地存储

    localStorage的优势 1.localStorage拓展了cookie的4K限制 2.localStorage会可以将第一次请求的数据直接存储到本地,这个相当于一个5M大小的针对于前端页面的数 ...

  5. 第三节:Action向View传值的四种方式(ViewData、ViewBag、TempData、Model)

    简  介 在前面的章节中,我们已经很清楚,MVC工作模型的流程,Controller中的Action接收到客户端的请求,处理后要将数据返回给View,那么Action中是如何将数据返回给View的,二 ...

  6. 第四节: EF调用存储过程的通用写法和DBFirst模式子类调用的特有写法

    一. 背景 上一个章节,介绍了EF调用两类SQL语句,主要是借助 ExecuteSqlCommand  和 SqlQuery 两个方法来完成,在本章节主要是复习几类存储过程的写法和对应的EF调用这几类 ...

  7. [Android] 免费天气预报接口

    [Android] 免费天气预报接口 这是 国家气象局提供的天气预报接口 [免费] 当然,网上有很多的收费API或者每天定次数的接口 使用 国家气象局 的步骤如下: 1.首先获取城市ID号 北京:10 ...

  8. WEB内容换行

    word-wrap:break-word 单词间换行 word-break:break-all 单词内也可以换行 white-space属性指定元素内的空白怎样处理 normal 默认.空白会被浏览器 ...

  9. 关于JS中的常用表单验证+正则表达式

    一.非空验证 trim:去空格(去掉前后的空格),任何字符串都可以用这个方法.写法为:if(v.trim().length==0),表示如果去掉空格后的字符串的长度为0. <body> & ...

  10. ve2.0 v-for循环报错的解决方案

    <li v-for="(item,index) in mokeData" class="page" :key="index"> ...