During a code review of a customers code base I noticed they were doing a lot of JSON serialization and deserialization actions. As the JSON data was quite large, this caused high memory pressure. Way to much time was spent in the garbage collector as too many (large) objects were allocated.
To minimize memory usage and the number of objects allocated, Json.NET supports serializing and deserializing directly to a stream.
Here is a code snippet:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |