Skip to content

Instantly share code, notes, and snippets.

@jeremychone
Last active November 12, 2019 14:33
Show Gist options
  • Save jeremychone/700b6ed721565e2488a2cff60b5ad749 to your computer and use it in GitHub Desktop.
Save jeremychone/700b6ed721565e2488a2cff60b5ad749 to your computer and use it in GitHub Desktop.
const router = require('cmdrouter');
const fs = require('fs-extra');
const yamljs = require('yamljs');
const jsyaml = require('js-yaml');
// USAGE:
// `node yaml-vs-json-perf write` to create the data data yaml and data.json files, and stringify perf measure.
// `node yaml-vs-json-perf read` to perf measure the parsing.
router({ read, write }).route();
async function write() {
const itemsCount = 100000;
const subItemsCount = 3;
let start, yamlString;
const docObj = {};
docObj.items = [];
// create the docObj
for (let i = 0; i < itemsCount; i++) {
const item = { i };
item.name = `name ${i}`;
item.description = `description for ${i}`;
item.subItems = [];
for (let j = 0; j < subItemsCount; j++) {
item.subItems.push(`subItem ${i}-${j}`);
}
docObj.items.push(item);
}
// json
start = now();
const jsonString = JSON.stringify(docObj, null, ' ');
console.log(`json stringify ${Math.round(now() - start)}ms`);
await fs.writeFile('data.json', jsonString, 'utf8');
// Generate js-yaml
start = now();
yamlString = jsyaml.dump(docObj, { indent: 2 });
console.log(`js-yaml stringify ${Math.round(now() - start)}ms`);
await fs.writeFile('data-jsyaml.yaml', yamlString, 'utf8');
// Generate yamljs
start = now();
yamlString = yamljs.stringify(docObj, 100, 2);
console.log(`yamljs stringify ${Math.round(now() - start)}ms`);
await fs.writeFile('data-yamljs.yaml', yamlString, 'utf8');
}
async function read() {
let start;
const jsonString = await fs.readFile('data.json', 'utf8');
const jsyamlString = await fs.readFile('data-jsyaml.yaml', 'utf8');
const yamljsString = await fs.readFile('data-yamljs.yaml', 'utf8');
// pick one to make sure that both are measures with the same input
const yamlString = yamljsString;
// json
start = now();
JSON.parse(jsonString);
console.log(`json parsing ${Math.round(now() - start)}ms`);
// js-yaml
start = now();
jsyaml.load(yamlString);
console.log(`js-yaml parsing ${Math.round(now() - start)}ms`);
// yamljs
start = now();
yamljs.parse(yamlString);
console.log(`yamljs parsing ${Math.round(now() - start)}ms`);
}
function now() {
var hrTime = process.hrtime();
return hrTime[0] * 1000 + hrTime[1] / 1000000;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment