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 ...
随机推荐
- Pandas系列(十二)-可视化详解
目录 1. 折线图 2. 柱状图 3. 直方图 4. 箱线图 5. 区域图 6. 散点图 7. 饼图六边形容器图 数据分析的结果不仅仅只是你来看的,更多的时候是给需求方或者老板来看的,为了更直观地看出 ...
- CMDB资产管理系统开发【day27】:理解RESTful架构
理解RESTful架构 越来越多的人开始意识到,网站即软件,而且是一种新型的软件. 这种"互联网软件"采用客户端/服务器模式,建立在分布式体系上,通过互联网通信,具有高延时(hig ...
- 点评cat系列-应用集成
========================消息的基本属性========================消息的几个属性:type: 定义消息的 category, 比如 SQL 或 RPC 或 ...
- .NET面试题系列(十七)前端面试
JavaScript js如何实现继承 CSS 行内元素和块状元素的区别 CSS让2个DIV在同一行显示的解决方法 在CSS中,div属于块级元素,每个块级元素默认占一行高度,一行内添加一个块级 ...
- EffectiveC++ 第3章 资源管理
我根据自己的理解,对原文的精华部分进行了提炼,并在一些难以理解的地方加上了自己的"可能比较准确"的「翻译」. Chapter 3 资源管理 条款13: 以对象管理资源 有时即使你顺 ...
- luogu P5294 [HNOI2019]序列
传送门 这个什么鬼证明直接看uoj的题解吧根本不会证明 首先方案一定是若干段等值的\(B\),然后对于一段,\(B\)的值应该是\(A\)的平均值.这个最优方案是可以线性构造的,也就是维护以区间平均值 ...
- python 模块 SQLalchemy
SQLalchemy 概述: # &&&&&&&&&&&&&&&&&am ...
- php7 + 新特性 部分
三目运算符: 以前:$type = isset($_GET['type']) ? $_GET['type'] : '测试'; php7.0: $type = $_GET['type'] ?? '测试' ...
- 写给自己看的vue
学习过程:自学(个人demo驱动),论坛,qq群多少听到vue,react(很抱歉只弄了hello world demo 虚拟dom 也是概念 到目前也没弄清楚)这类框架(工作经历前后端都折腾,老板指 ...
- Machine Schedule poj1325
Machine Schedule Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 17454 Accepted: 7327 ...