Skip to content

Instantly share code, notes, and snippets.

@creationix
Forked from bjouhier/benchCallbacks.js
Created April 12, 2012 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save creationix/2370779 to your computer and use it in GitHub Desktop.
Save creationix/2370779 to your computer and use it in GitHub Desktop.
streamline vs. callbacks bench
"use strict";
var fs = require('fs');
var cache = {}, hit = 0, missed = 0;
function load(name, cb) {
var res = cache[name];
if (res) {
process.nextTick(function() {
hit++;
cb(null, res);
});
} else {
fs.readFile(name, function(err, data) {
missed++;
cb(null, cache[name] = data);
});
}
}
var count = 1000000;
function bench(cb) {
var total = 0;
function loop(i) {
if (i === count) {
cb(null, total);
} else {
load(__dirname + '/benchCallbacks.js', function(err, data) {
if (err) return cb(err);
total += data.length;
loop(i + 1);
})
}
}
loop(0);
}
var t0 = Date.now();
bench(function(err, result) {
if (err) throw err;
console.log('hit=' + hit + ', missed=' + missed + ', result=' + result);
console.log('elapsed: ' + (Date.now() - t0));
});
"use strict";
var fs = require('fs');
var cache = {}, hit = 0, missed = 0;
function load(name, cb) {
var res = cache[name];
if (res) {
hit++;
cb(null, res);
} else {
fs.readFile(name, function(err, data) {
missed++;
cb(null, cache[name] = data);
});
}
}
var count = 1000000;
function bench(cb) {
var total = 0;
function loop(i) {
var async;
while (async !== true) {
async = undefined;
if (i === count) {
cb(null, total);
} else {
load(__dirname + '/benchCallbacks.js', function(err, data) {
if (err) return cb(err);
total += data.length;
if (async) {
loop(i + 1);
} else {
async = false;
i++;
}
});
}
if (async !== false) {
async = true;
}
}
}
loop(0);
}
var t0 = Date.now();
bench(function(err, result) {
if (err) throw err;
console.log('hit=' + hit + ', missed=' + missed + ', result=' + result);
console.log('elapsed: ' + (Date.now() - t0));
});
"use strict";
var fs = require('fs');
var cache = {}, hit = 0, missed = 0;
function load(name, _) {
var res = cache[name];
if (res) {
hit++;
return res;
} else {
missed++;
return cache[name] = fs.readFile(name, _);
}
}
var count = 1000000;
function bench(_) {
var total = 0;
for (var i = 0; i < count; i++) {
var res = load(__dirname + '/benchCallbacks.js', _);
total += res.length;
}
return total;
}
var t0 = Date.now();
var result = bench(_);
console.log('hit=' + hit + ', missed=' + missed + ', result=' + result);
console.log('elapsed: ' + (Date.now() - t0));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment