Click or drag to resize
Json.NETPerformance Tips
 

Json.NET Schema has been designed for high performance. Here are some tips to rapidly validate JSON data.

Reuse JSchemas

The best way to improve performance is to load a JSON Schema into JSchema once and reuse it each time you validate JSON. Reusing a JSchema eliminates the time required to parse and load the schema from JSON every time you validate data.

A loaded JSchema is thread-safe for validation and can be safely cached once and reused for the life-time of an application or website.

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 Schema supports validating JSON as it is being read from or written to a stream. Validating JSON a piece at a time, instead of loading the entire JSON document 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.

Validate Stream
 1string schemaJson = @"{
 2  'description': 'A person',
 3  'type': 'object',
 4  'properties': {
 5    'name': {'type': 'string'},
 6    'hobbies': {
 7      'type': 'array',
 8      'items': {'type': 'string'}
 9    }
10  }
11}";
12
13JSchema schema = JSchema.Parse(schemaJson);
14
15using (StreamReader s = File.OpenText(@"c:\bigdata.json"))
16using (JSchemaValidatingReader reader = new JSchemaValidatingReader(new JsonTextReader(s)))
17{
18    // assign schema and setup event handler
19    reader.Schema = schema;
20    reader.ValidationEventHandler += (sender, args) => { Console.WriteLine(args.Message); };
21
22    // bigdata.json will be validated without loading the entire document into memory
23    while (reader.Read())
24    {
25    }
26}
Benchmarks

Json.NET Schema validation is significantly faster than Json.NET's obsolete JsonSchema.

It is more than twice as fast as the .NET Framework's XmlSchema when validating equivalent XML with an XML Schema.

performance

The source code for this benchmark can be found in PerformanceComparisonTests.cs on GitHub.

See Also