Skip to content

Instantly share code, notes, and snippets.

@vojtajina
Created October 19, 2012 05:18
Show Gist options
  • Save vojtajina/3916369 to your computer and use it in GitHub Desktop.
Save vojtajina/3916369 to your computer and use it in GitHub Desktop.
async.forEach vs. sync forEach (very lame)
var async = require('async');
var fs = require('fs');
var files = [];
while(files.length < 100000) {
files.push('/some/file' + files.length);
}
var queue = [];
var next = function() {
if (queue.length) {
queue.shift()();
}
};
var benchSync = function() {
var start = Date.now();
var pending = 0;
var finish = function() {
if (!--pending) {
console.log('SYNC:', Date.now() - start);
next();
}
};
files.forEach(function(path) {
pending++;
fs.stat(path, finish);
});
};
var benchAsync = function() {
var start = Date.now();
var pending = 0;
var finish = function() {
if (!--pending) {
console.log('ASYNC:', Date.now() - start);
next();
}
};
async.forEach(files, function(path) {
pending++;
fs.stat(path, finish);
});
};
while(queue.length < 10) {
queue.push(benchAsync);
queue.push(benchSync);
}
next();
@vojtajina
Copy link
Author

$ node test.js
ASYNC: 3401
SYNC: 3410
ASYNC: 3414
SYNC: 3433
ASYNC: 3395
SYNC: 3414
ASYNC: 3404
SYNC: 3391
ASYNC: 3420
SYNC: 3444

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment