Make `JSON.stringify` more fast with JSON Schema

JSON.stringify is used by web server like expressjs for trasform object into json response. Fastify (an expressjs alternative) is 3x faster because use
fast-json-stringify, fast-json-stringify requires a JSON Schema Draft 7 input to generate a fast stringify function. With the JSON schema, fast-json-stringify already know the structure of the object and can create a template string with just some placeholder for the value to replace on stringify.

JavaScript could be have a JSON.Schema that accept a JSON schema in the same way, ad return an optimized stringify function, eg::

const stringify = JSON.Schema({
  title: 'Example Schema',
  type: 'object',
  properties: {
    firstName: {
      type: 'string'
    },
    lastName: {
      type: 'string'
    },
    age: {
      description: 'Age in years',
      type: 'integer'
    }
  }
})

console.log(stringify({
  firstName: 'Foo',
  lastName: 'Bar',
  age: 32
}))

output

{"firstName":"Foo","lastName":"Bar","age":32}

Optimized stringify method internally has the template of the structure with the placeholder, eg:

{"firstName":"$0","lastName":"$1","age":$2}

Related thread for parsing instead of serialisation: Schema-based JSON parsing?

1 Like