Skip to content

Instantly share code, notes, and snippets.

@Redsandro
Last active October 12, 2015 12:53
Show Gist options
  • Save Redsandro/3e661d31a5934b6fb844 to your computer and use it in GitHub Desktop.
Save Redsandro/3e661d31a5934b6fb844 to your computer and use it in GitHub Desktop.
Node.js xml to json parsers benchmark thingie
/*
* Benchmarking xml to json parsers
* @author Sander AKA Redsandro (http://www.Redsandro.com)
*/
var path = require('path');
var util = require('util');
var fs = require('fs');
var q = require('q');
q.longStackSuppor = true;
var xml2js = require('xml2js'); // pure Javascript // 0.4.10
var xml2jsp = new xml2js.Parser();
var xml2json = require('xml2json'); // https://github.com/buglabs/node-xml2json // Fast! // 0.5.1
var x2je = require('xml2js-expat'); // https://github.com/Poetro/node-xml2js-expat // Faster! // 0.2.2
var rapidx2j = require('rapidx2j'); // https://github.com/damirn/rapidx2j // Fastest? // 0.0.8
var fileName = 'huge.xml';
var pwd = path.dirname(require.main.filename);
var file = path.join(pwd, fileName);
var xml = fs.readFileSync(file, 'utf8');
var timeMs;
q(true)
// Try xml2json 5 times...
.then(doXml2json)
.then(doXml2json)
.then(doXml2json)
.then(doXml2json)
.then(doXml2json)
// Try xml-expat 5 times...
.then(doExpat)
.then(doExpat)
.then(doExpat)
.then(doExpat)
.then(doExpat)
// Try rapidx2j 5 times...
.then(doRapid)
.then(doRapid)
.then(doRapid)
.then(doRapid)
.then(doRapid)
.then(function(json) {
console.log('Done.');
return;
})
.fail(function(e) {
console.log('Failed with error. :(');
console.log(e.stack);
})
.done();
function doExpat() {
return q.nfcall(function(cb) {
var json;
var modName = 'xml2js-expat 0.2.2';
console.time(modName);
var parser = new x2je.Parser(function(result, error) {
if (!error) {
json = result;
console.timeEnd(modName);
}
else {
console.error(error);
}
});
if (parser.parseString(xml)) {
cb(null, json);
} else {
cb(new Error(util.format('node-xml2js-expat: parse error: "%s"', parser.getError() )));
}
});
}
function doRapid() {
return q.nfcall(function(cb) {
var json;
var modName = 'rapidx2j 0.0.9';
//console.log(util.format('Trying %s...', modName));
console.time(modName);
try {
json = rapidx2j.parse(xml);
//console.log(json);
console.timeEnd(modName);
cb(null, json);
}
catch (e) {
cb(e);
}
});
}
function doXml2json() {
return q.nfcall(function(cb) {
var json;
var modName = 'xml2json 0.5.1';
console.time(modName);
try {
json = xml2json.toJson(xml, {object: true});
// console.log(JSON.stringify(json));
console.timeEnd(modName);
cb(null, json);
}
catch (e) {
cb(e);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment