Skip to content

Instantly share code, notes, and snippets.

@sudsy sudsy/trycatchperformance
Last active Dec 22, 2015

Embed
What would you like to do?
Performance Testing of asynchronous functions using try catch blocks node.js see: http://www.lighthouselogic.com/try-catch-performance-in-node-js/
var Benchmark = require('benchmark');
var fs = require("fs");
var j_ = 10000000;
function intensive(){
var s = 0;
for (var i = 0; i < j_; i++) s = i;
for (var i = 0; i < j_; i++) s = i;
for (var i = 0; i < j_; i++) s = i;
for (var i = 0; i < j_; i++) s = i;
}
function readJsonWithoutTryCatchIntensive(filename, callback) {
fs.readFile(filename, function (err, content) {
if (err) {
return callback(err);
}
var data = JSON.parse(content.toString());
intensive();
return callback(null, data);
});
}
function readJsonWithTryCatchIntensive(filename, callback) {
fs.readFile(filename, function (err, content) {
if (err) {
return callback(err);
}
try {
var data = JSON.parse(content.toString());
intensive();
} catch (e) {
return callback(e);
}
return callback(null, data);
});
}
function readJsonWithTryCatch(filename, callback) {
fs.readFile(filename, function (err, content) {
if (err) {
return callback(err);
}
var data = JSON.parse(content.toString());
try {
var s = 0;
for (var i = 0; i < j_; i++) s = i;
for (var i = 0; i < j_; i++) s = i;
for (var i = 0; i < j_; i++) s = i;
for (var i = 0; i < j_; i++) s = i;
} catch (e) {
return callback(e);
}
return callback(null, data);
});
}
function readJsonWithoutTryCatch(filename, callback) {
fs.readFile(filename, function (err, content) {
if (err) {
return callback(err);
}
var data = JSON.parse(content.toString());
var s = 0;
for (var i = 0; i < j_; i++) s = i;
for (var i = 0; i < j_; i++) s = i;
for (var i = 0; i < j_; i++) s = i;
for (var i = 0; i < j_; i++) s = i;
return callback(null, data);
});
}
var suite = new Benchmark.Suite;
// add tests
suite.add('Control (readJSONWithoutTryCatchIntensive) ', function(deferred) {
readJsonWithoutTryCatchIntensive("./test.json", function(){
deferred.resolve();
});
}, {'defer': true}).add('readJSONWithTryCatchIntensive', function(deferred) {
readJsonWithTryCatchIntensive("./test.json", function(){
deferred.resolve();
});
}, {'defer': true}).add('readJSONWithTryCatch', function(deferred) {
readJsonWithTryCatch("./test.json", function(){
deferred.resolve();
});
}, {'defer': true}).add('readJSONWithoutTryCatch', function(deferred) {
readJsonWithoutTryCatch("./test.json", function(){
deferred.resolve();
});
}, {'defer': true}).on('cycle', function(event) {
console.log(String(event.target));
}).on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
}).run({ 'async': true });
// Slow!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.