Json.NET Performance Tips

时间:2022-09-21 17:55:13

原文: 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&period;js&colon; 10 performance tips from LinkedIn Mobile

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

  5. &lbrack;Javascript&rsqb;3&period; Improve you speed&excl; Performance Tips

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

  6. &lbrack;Angular&rsqb; Some performance tips

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

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

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

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

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

  9. MySQL5&period;7 JSON实现简介

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

随机推荐

  1. 传智播客JavaWeb day07、day08-自定义标签&lpar;传统标签和简单标签&rpar;、mvc设计模式、用户注册登录注销

    第七天的课程主要是讲了自定义标签.简单介绍了mvc设计模式.然后做了案例 1. 自定义标签 1.1 为什么要有自定义标签 前面所说的EL.JSTL等技术都是为了提高jsp的可读性.可维护性.方便性而取 ...

  2. Spring JDBC主从数据库配置

    通过昨天学习的自定义配置注释的知识,探索了解一下web主从数据库的配置: 背景:主从数据库:主要是数据上的读写分离: 数据库的读写分离的好处? 1. 将读操作和写操作分离到不同的数据库上,避免主服务器 ...

  3. bzoj 1926&colon; &lbrack;Sdoi2010&rsqb;粟粟的书架

    #include<cstdio> #include<iostream> #define N 201 #define M 500008 using namespace std; ...

  4. GO&colon;格式化代码

    http://www.ituring.com.cn/article/39380 Go 开发团队不想要 Go 语言像许多其它语言那样总是在为代码风格而引发无休止的争论,浪费大量宝贵的开发时间,因此他们制 ...

  5. mysql同时update多行

    当我们只更新一个字段时的语法如下: UPDATE mytable     SET myfield = CASE other_field         WHEN 1 THEN 'value'     ...

  6. Apache Beam 剖析

    1.概述 在大数据的浪潮之下,技术的更新迭代十分频繁.受技术开源的影响,大数据开发者提供了十分丰富的工具.但也因为如此,增加了开发者选择合适工具的难度.在大数据处理一些问题的时候,往往使用的技术是多样 ...

  7. gnome 3 美化

    首先,去http://gnome-look.org/找到需要的主题,然后手动安装或者用下载到的主题包里的脚本安装 手动安装对应路径如下: 鼠标,图标主题解压放置:~/.icons或/usr/share ...

  8. WeakHashMap

    WeakHashMap 今天在具体业务的时候看到HashMap和WeakHashMap的区别.因为PHP语言并没有这种概念.所以很好奇做了一下研究. WeakHashMap WeakHashMap所谓 ...

  9. js处理数字加后缀w

    num > 9999 ? (Math.floor(num/1000)/10) + 'w' : num

  10. &period;Net&lpar;c&num;&rpar;加密解密工具类:

    /// <summary> /// .Net加密解密帮助类 /// </summary> public class NetCryptoHelper { #region des实 ...