Which is Better Faster JSON Stringify Library?
fast-safe-stringify vs json-stringify-safe vs fast-json-stringify

1 Year
fast-safe-stringifyjson-stringify-safefast-json-stringify
What's Faster JSON Stringify Library?

Faster JSON Stringify Library is designed to improve the speed and efficiency of converting JavaScript objects or data into JSON string format. The process of converting JavaScript objects to JSON strings, known as JSON stringify, can sometimes be a performance bottleneck, especially when dealing with large or complex objects. A faster JSON stringify library aims to optimize this process by implementing more efficient algorithms or techniques to speed up the conversion process.

NPM Package Downloads Trend
Github Stars Ranking
Stat Detail
Package
Weekly Downloads
Github Stars
Open Issues
Last Commit
License
json-stringify-safe23,052,79254273 years agoISC License
fast-safe-stringify13,425,439341102 years agoMIT License
fast-json-stringify2,169,9733,354237 days agoMIT License
Feature Comparison
Featuresfast-safe-stringifyjson-stringify-safefast-json-stringify
Size
fast-safe-stringify is a compact package, making it suitable for projects with strict size constraints.
json-stringify-safe is also small in size, making it a good choice for projects where minimizing bundle size is essential.
fast-json-stringify is known for its ultra-small size, making it an excellent choice for applications with the most stringent size limitations.
Consistency
fast-safe-stringify provides consistent JSON stringification, handling circular references and other edge cases reliably.
json-stringify-safe is consistent in its JSON stringification, ensuring data integrity even in complex scenarios.
fast-json-stringify also maintains consistency and predictability in JSON stringification, making it a dependable choice for circular references and complex objects.
Mutability
fast-safe-stringify preserves the immutability of the original object during stringification.
json-stringify-safe, like fast-safe-stringify, does not alter the original object, ensuring that data remains unchanged.
fast-json-stringify maintains the mutability of the original object and does not modify it during stringification.
Extensibility
fast-safe-stringify is not particularly extensible and lacks advanced customization options.
json-stringify-safe is not highly extensible and may not provide extensive customization for the stringification process.
fast-json-stringify offers limited extensibility, making it more suitable for simple use cases where advanced customization is not a requirement.
Maintenance
fast-safe-stringify has received regular maintenance and updates, ensuring compatibility with the latest Node.js and JavaScript environments.
json-stringify-safe may have seen fewer recent updates, which could raise concerns about its long-term maintenance and compatibility.
fast-json-stringify has a good maintenance record, with ongoing updates to support the latest Node.js and JavaScript versions.
Learning Curve
fast-safe-stringify is easy to use and has a minimal learning curve, suitable for developers of all levels.
json-stringify-safe is also user-friendly and approachable, with a low learning curve that accommodates developers, including beginners.
fast-json-stringify is known for its simplicity, making it a great choice for those who prefer an easy-to-use JSON stringification solution.
Ecosystem
fast-safe-stringify is compatible with the broader Node.js and JavaScript ecosystem, integrating well with other libraries and tools.
json-stringify-safe is also part of the larger ecosystem, making it a reliable choice for a wide range of projects.
fast-json-stringify fits seamlessly into the Node.js and JavaScript ecosystem, ensuring compatibility with various other packages and tools.
NPM Package Introudction

fast-safe-stringify

Safe and fast serialization alternative to JSON.stringify.

Gracefully handles circular structures instead of throwing in most cases. It could return an error string if the circular object is too complex to analyze, e.g. in case there are proxies involved.

Provides a deterministic ("stable") version as well that will also gracefully handle circular structures. See the example below for further information.

Usage

The same as JSON.stringify.

stringify(value[, replacer[, space[, options]]])

const safeStringify = require('fast-safe-stringify')
const o = { a: 1 }
o.o = o

console.log(safeStringify(o))
// '{"a":1,"o":"[Circular]"}'
console.log(JSON.stringify(o))
// TypeError: Converting circular structure to JSON

function replacer(key, value) {
  console.log('Key:', JSON.stringify(key), 'Value:', JSON.stringify(value))
  // Remove the circular structure
  if (value === '[Circular]') {
    return
  }
  return value
}

// those are also defaults limits when no options object is passed into safeStringify
// configure it to lower the limit.
const options = {
  depthLimit: Number.MAX_SAFE_INTEGER,
  edgesLimit: Number.MAX_SAFE_INTEGER
};

const serialized = safeStringify(o, replacer, 2, options)
// Key: "" Value: {"a":1,"o":"[Circular]"}
// Key: "a" Value: 1
// Key: "o" Value: "[Circular]"
console.log(serialized)
// {
//  "a": 1
// }

Using the deterministic version also works the same:

const safeStringify = require('fast-safe-stringify')
const o = { b: 1, a: 0 }
o.o = o

console.log(safeStringify(o))
// '{"b":1,"a":0,"o":"[Circular]"}'
console.log(safeStringify.stableStringify(o))
// '{"a":0,"b":1,"o":"[Circular]"}'
console.log(JSON.stringify(o))
// TypeError: Converting circular structure to JSON

A faster and side-effect free implementation is available in the [safe-stable-stringify][] module. However it is still considered experimental due to a new and more complex implementation.

Replace strings constants

  • [Circular] - when same reference is found
  • [...] - when some limit from options object is reached

Differences to JSON.stringify

In general the behavior is identical to JSON.stringify. The replacer and space options are also available.

A few exceptions exist to JSON.stringify while using toJSON or replacer:

Regular safe stringify

  • Manipulating a circular structure of the passed in value in a toJSON or the replacer is not possible! It is possible for any other value and property.

  • In case a circular structure is detected and the replacer is used it will receive the string [Circular] as the argument instead of the circular object itself.

Deterministic ("stable") safe stringify

  • Manipulating the input object either in a toJSON or the replacer function will not have any effect on the output. The output entirely relies on the shape the input value had at the point passed to the stringify function!

  • In case a circular structure is detected and the replacer is used it will receive the string [Circular] as the argument instead of the circular object itself.

A side effect free variation without these limitations can be found as well (safe-stable-stringify). It is also faster than the current implementation. It is still considered experimental due to a new and more complex implementation.

Benchmarks

Although not JSON, the Node.js util.inspect method can be used for similar purposes (e.g. logging) and also handles circular references.

Here we compare fast-safe-stringify with some alternatives: (Lenovo T450s with a i7-5600U CPU using Node.js 8.9.4)

fast-safe-stringify:   simple object x 1,121,497 ops/sec ±0.75% (97 runs sampled)
fast-safe-stringify:   circular      x 560,126 ops/sec ±0.64% (96 runs sampled)
fast-safe-stringify:   deep          x 32,472 ops/sec ±0.57% (95 runs sampled)
fast-safe-stringify:   deep circular x 32,513 ops/sec ±0.80% (92 runs sampled)

util.inspect:          simple object x 272,837 ops/sec ±1.48% (90 runs sampled)
util.inspect:          circular      x 116,896 ops/sec ±1.19% (95 runs sampled)
util.inspect:          deep          x 19,382 ops/sec ±0.66% (92 runs sampled)
util.inspect:          deep circular x 18,717 ops/sec ±0.63% (96 runs sampled)

json-stringify-safe:   simple object x 233,621 ops/sec ±0.97% (94 runs sampled)
json-stringify-safe:   circular      x 110,409 ops/sec ±1.85% (95 runs sampled)
json-stringify-safe:   deep          x 8,705 ops/sec ±0.87% (96 runs sampled)
json-stringify-safe:   deep circular x 8,336 ops/sec ±2.20% (93 runs sampled)

For stable stringify comparisons, see the performance benchmarks in the safe-stable-stringify readme.

Protip

Whether fast-safe-stringify or alternatives are used: if the use case consists of deeply nested objects without circular references the following pattern will give best results. Shallow or one level nested objects on the other hand will slow down with it. It is entirely dependant on the use case.

const stringify = require('fast-safe-stringify')

function tryJSONStringify (obj) {
  try { return JSON.stringify(obj) } catch (_) {}
}

const serializedString = tryJSONStringify(deep) || stringify(deep)

Acknowledgements

Sponsored by nearForm

License

MIT