Created
July 24, 2017 19:37
-
-
Save lukashavrlant/107a36097194f608b5c71ae569318009 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fastSafeStringify = require('fast-safe-stringify'); | |
var fastJsonStringify = require('fast-json-stringify'); | |
var fastStableStringify = require('fast-stable-stringify'); | |
const object = { | |
foo: "bar", | |
number: 12345, | |
bool: true, | |
name: "some really long string", | |
message: "this is really weird" | |
}; | |
const scheme = { | |
type: 'object', | |
properties: { | |
foo: {type: "string"}, | |
name: {type: "string"}, | |
message: {type: "string"}, | |
number: {type: "number"}, | |
bool: {type: "boolean"} | |
} | |
}; | |
const count = 1000 * 1000; | |
console.time('JSON.stringify'); | |
for (let i = 0; i < count; i++) { | |
JSON.stringify(object); | |
} | |
console.timeEnd('JSON.stringify'); | |
console.time('fastSafeStringify'); | |
for (let i = 0; i < count; i++) { | |
fastSafeStringify(object); | |
} | |
console.timeEnd('fastSafeStringify'); | |
console.time('luhaStringify'); | |
for (let i = 0; i < count; i++) { | |
luhaStringify(object); | |
} | |
console.timeEnd('luhaStringify'); | |
console.time('fastStableStringify'); | |
for (let i = 0; i < count; i++) { | |
fastStableStringify(object); | |
} | |
console.timeEnd('fastStableStringify'); | |
console.time('fastJsonStringify'); | |
const fastJsonStringifyFn = fastJsonStringify(scheme); | |
for (let i = 0; i < count; i++) { | |
fastJsonStringifyFn(object); | |
} | |
console.timeEnd('fastJsonStringify'); | |
function luhaStringify(object) { | |
if (object) { | |
let first = true; | |
let str = "{"; | |
for (let key of Object.keys(object)) { | |
if (first) { | |
str += '"' + key + '"'; //`"${key}": ` | |
first = false; | |
} else { | |
str += ', "' + key + '": '; // `, "${key}": ` | |
} | |
if (typeof object[key] === 'string') { | |
str += '"' + object[key] + '"'; //`"${object[key]}"`; | |
} else { | |
str += object[key].toString(); // `${object[key]}`; | |
} | |
} | |
return str + "}"; | |
} else { | |
throw new Error(`Cannot stringify empty object`); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment