gitmyhub

fast-json-stringify

JavaScript ★ 3.7k updated 1d ago

2x faster than JSON.stringify()

JavaScript library that serializes objects to JSON up to 2.5x faster than JSON.stringify by using a pre-declared JSON Schema to generate a specialized serializer function for your data shape.

JavaScriptNode.jsJSON Schemasetup: easycomplexity 2/5

fast-json-stringify is a JavaScript library that converts objects to JSON text faster than the built-in JSON.stringify function. The speed gain comes from a trade-off: instead of inspecting the object at runtime to figure out its structure, you describe the structure in advance using a JSON Schema, and the library uses that description to generate a specialized serializer function. That generated function skips the type-checking work that JSON.stringify does every time it runs.

The performance benefit is most pronounced for small objects. The benchmark numbers in the README show short strings serializing at around 29 million operations per second compared to 12 million for JSON.stringify, and plain objects at around 7 million versus 4.5 million. For large arrays the advantage disappears; the library is actually slower than JSON.stringify on those, and the README states this limitation plainly.

Usage follows a two-step pattern: call the library with your schema to get back a stringify function, then call that function on your data. The schema describes the types of each field using JSON Schema Draft 7 format. Fields not present in the schema are omitted from the output. Required fields that are missing will throw an error. The library also handles JavaScript-specific types that do not have direct JSON equivalents: Date objects are converted to ISO 8601 strings, RegExp values are converted to strings, and BigInt values are serialized as integers.

Additional features documented in the README include support for schema references (so you can reuse sub-schemas), anyOf and oneOf for fields that can hold more than one type, a configurable rounding mode for numbers that are supposed to be integers but arrive as floats, and a large-array mode that changes the internal mechanism for arrays above 20,000 items. A standalone mode can write the generated function to a file so it can be loaded without the library at runtime. The library is part of the Fastify web framework ecosystem and is licensed under the MIT license.

Where it fits