Click or drag to resize
Json.NETPerformance Tips
 

Out of the box Json.NET is faster than DataContractJsonSerializer and JavaScriptSerializer. Here are some tips to make it go even faster.

Optimize Memory Usage

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.

Deserialize String
1HttpClient client = new HttpClient();
2
3// read the json into a string
4// string could potentially be very large and cause memory problems
5string json = client.GetStringAsync("http://www.test.com/large.json").Result;
6
7Person p = JsonConvert.DeserializeObject<Person>(json);
Deserialize Stream
 1HttpClient client = new HttpClient();
 2
 3using (Stream s = client.GetStreamAsync("http://www.test.com/large.json").Result)
 4using (StreamReader sr = new StreamReader(s))
 5using (JsonReader reader = new JsonTextReader(sr))
 6{
 7    JsonSerializer serializer = new JsonSerializer();
 8
 9    // read the json from a stream
10    // json size doesn't matter because only a small piece is read at a time from the HTTP request
11    Person p = serializer.Deserialize<Person>(reader);
12}
JsonConverters

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.

Use JsonConverter with JsonConverterAttribute
 1[JsonConverter(typeof(PersonConverter))]
 2public class Person
 3{
 4    public Person()
 5    {
 6        Likes = new List<string>();
 7    }
 8
 9    public string Name { get; set; }
10    public IList<string> Likes { get; private set; }
11}

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.

Use JsonConverter with IContractResolver
 1public class ConverterContractResolver : DefaultContractResolver
 2{
 3    public new static readonly ConverterContractResolver Instance = new ConverterContractResolver();
 4
 5    protected override JsonContract CreateContract(Type objectType)
 6    {
 7        JsonContract contract = base.CreateContract(objectType);
 8
 9        // this will only be called once and then cached
10        if (objectType == typeof(DateTime) || objectType == typeof(DateTimeOffset))
11        {
12            contract.Converter = new JavaScriptDateTimeConverter();
13        }
14
15        return contract;
16    }
17}

The IContractResolver in the example above will set all DateTimes to use the JavaScriptDateConverter.

Manually Serialize

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.

Manually serialize using JsonTextWriter
 1public static string ToJson(this Person p)
 2{
 3    StringWriter sw = new StringWriter();
 4    JsonTextWriter writer = new JsonTextWriter(sw);
 5
 6    // {
 7    writer.WriteStartObject();
 8
 9    // "name" : "Jerry"
10    writer.WritePropertyName("name");
11    writer.WriteValue(p.Name);
12
13    // "likes": ["Comedy", "Superman"]
14    writer.WritePropertyName("likes");
15    writer.WriteStartArray();
16    foreach (string like in p.Likes)
17    {
18        writer.WriteValue(like);
19    }
20    writer.WriteEndArray();
21
22    // }
23    writer.WriteEndObject();
24
25    return sw.ToString();
26}

If performance is important and you don't mind writing more code to get it, then this is your best choice. You can read more about using JsonReader/JsonWriter here: Basic Reading and Writing JSON

Benchmarks
performance
See Also