Performance Tips |
Json.NET Schema has been designed for high performance. Here are some tips to rapidly validate JSON data.
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.
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.
string schemaJson = @"{ 'description': 'A person', 'type': 'object', 'properties': { 'name': {'type': 'string'}, 'hobbies': { 'type': 'array', 'items': {'type': 'string'} } } }"; JSchema schema = JSchema.Parse(schemaJson); using (StreamReader s = File.OpenText(@"c:\bigdata.json")) using (JSchemaValidatingReader reader = new JSchemaValidatingReader(new JsonTextReader(s))) { // assign schema and setup event handler reader.Schema = schema; reader.ValidationEventHandler += (sender, args) => { Console.WriteLine(args.Message); }; // bigdata.json will be validated without loading the entire document into memory while (reader.Read()) { } }
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.
The source code for this benchmark can be found in PerformanceComparisonTests.cs on GitHub.