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();
- }
Json.NET Performance Tips的更多相关文章
- Android 性能优化(19)*代码优化11条技巧:Performance Tips
Performance Tips 1.In this document Avoid Creating Unnecessary Objects 避免多余的对象 Prefer Static Over Vi ...
- SQL Server performance tips
Refer to: http://harriyott.com/2006/01/sql-server-performance-tips A colleague of mine has been look ...
- Performance tips
HTML5 Techniques for Optimizing Mobile Performance Scrolling Performance layout-performance
- 翻译--Blazing fast node.js: 10 performance tips from LinkedIn Mobile
1.避免使用同步代码: // Good: write files asynchronously fs.writeFile('message.txt', 'Hello Node', function ( ...
- [Javascript]3. Improve you speed! Performance Tips
/** Let inheritance help with memory efficiency */ function SignalFire(ID, startingLogs){ this.fireI ...
- [Angular] Some performance tips
The talk from here. 1. The lifecycle in Angular component: constructor vs ngOnInit: Constructor: onl ...
- 在C#中,Json的序列化和反序列化的几种方式总结
在这篇文章中,我们将会学到如何使用C#,来序列化对象成为Json格式的数据,以及如何反序列化Json数据到对象. 什么是JSON? JSON (JavaScript Object Notation) ...
- Visual Studio 2013下JSON可视化工具
Visual Studio 2013现在我们有个小工具可以实现JSON可视化,这样给我们调试JSON提供了便利. JSON这种数据格式已经比较流行,在WEB前端随处可见. 在你需要安装VS ...
- MySQL5.7 JSON实现简介
版权声明:本文由吴双桥原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/205 来源:腾云阁 https://www.qclo ...
随机推荐
- CMDB资产管理系统开发【day25】:windows客户端开发
1.目录结构 PS Y:\MadkingClient> tree /f 卷 netgame 的文件夹 PATH 列表 卷序列号为 ACE3-896E Y:. ├─bin │ NedStark.p ...
- EF CodeFirst系列(6)---配置1对1,1对多,多对多关系
这一节介绍EF CodeFirst模式中的1对0/1,1对多,多对多关系的配置,只有梳理清楚实体间的关系,才能进行愉快的开发,因此这节虽然很简单但是还是记录了一下. 1. 1对0/1关系配置 1. 通 ...
- DirectX11 With Windows SDK--16 流输出阶段
前言 在上一章,我们知道了如何使用几何着色器来重新组装图元,比如从一个三角形分裂成三个三角形.但是为了实现更高阶的分形,我们必须要从几何着色器拿到输出的顶点.这里我们可以使用可选的流输出阶段来拿到顶点 ...
- MySQL学习笔记(五)并发时经典常见的死锁原因及解决方法
MySQL都有什么锁? MySQL有三种锁的级别:页级.表级.行级. 表级锁:开销小,加锁快:不会出现死锁:锁定粒度大,发生锁冲突的概率最高,并发度最低. 行级锁:开销大,加锁慢:会出现死锁:锁定粒度 ...
- npm cnpm yarn
npm 如何下载指定版本的组件 先确保文件目录下含有 package.json 文件, 没有的话,可以通过 npm init 创建, 然后只需要在组件的后面加上 @2.8.1 版本号即可, 例如:re ...
- Django对于模型的数据操作
一.引入模型的包 from myApp.models import Grades,Students 二.查询所有数据 #objecs是类的隐藏属性:类名.objects.all()可以查询所有数据 G ...
- ng-app&data-ng-app
来源stackoverflow 区别:在验证html5时,ng-app会抛出一个错误,而对带data-前缀的特性不会抛出.其它方面这两个属性一样.
- 《css网站布局实录》(李超)——读书札记
1.web表现层技术 2.HTML链接设计思想 3.对信息进行合理的分析.分类与处理来创造商业价值. 4.头部描述浏览器所需信息,主体包含所需要展现的具体内容. 5.HTML(XHTML)XML 6. ...
- c++基础学习
1.输入输出函数(cout,cin) #include<iostream> int main() { using namespace std; cout<<"Come ...
- Python爬虫实战一之爬取QQ音乐
一.前言 前段时间尝试爬取了网易云音乐的歌曲,这次打算爬取QQ音乐的歌曲信息.网易云音乐歌曲列表是通过iframe展示的,可以借助Selenium获取到iframe的页面元素, 而QQ音乐采用的是 ...