Skip to content

Instantly share code, notes, and snippets.

@mizchi

mizchi/benchmark.js

Last active Sep 30, 2020
Embed
What would you like to do?
JSON, fast-json-stringify, superjson benchmark
// original: https://github.com/blitz-js/superjson/blob/main/benchmark.js
const Benchmark = require('benchmark');
const SuperJSON = require('./dist/').default;
const fastJson = require('fast-json-stringify');
const stringify = fastJson({
type: 'object',
required: ['a'],
additionalProperties: false,
properties: {
a: {
type: 'object',
required: ['x', 'y', 'z'],
additionalProperties: false,
properties: {
x: {
type: 'string',
},
y: {
type: 'number',
},
z: {
type: 'object',
required: ['arr'],
additionalProperties: false,
properties: {
arr: {
type: 'array',
items: {
type: 'string',
},
},
},
},
},
},
},
});
const instances = {
nested_json: {
a: {
x: 'v1huetoahuesoahu',
y: 189898,
z: { arr: ['a1111', 'b2222', 'c333'] },
},
},
};
const suite = new Benchmark.Suite('serialize & deserialize');
for (const [key, instance] of Object.entries(instances)) {
suite.add('JSON.stringify:' + key, () => {
JSON.parse(JSON.stringify(instance));
});
suite.add('fast-json-stringify:' + key, () => {
JSON.parse(stringify(instance));
});
suite.add('superjson:' + key, () => {
SuperJSON.deserialize(SuperJSON.serialize(instance));
});
}
suite.on('cycle', event => {
if (event.target.error) {
console.error(event.target.error);
process.exit(1);
}
console.log('' + event.target);
});
suite.run();
/*
JSON.stringify:nested_json x 494,214 ops/sec ±0.66% (92 runs sampled)
fast-json-stringify:nested_json x 708,988 ops/sec ±0.87% (94 runs sampled)
superjson:nested_json x 91,521 ops/sec ±1.22% (92 runs sampled)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment