Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Speed test of sort variants in Node
var _ = require('underscore');
var async = require('async');
var sumTime = {};
var sortarray = [];
var ARRAYCOUNT = 100000;
var INNERITERATIONS = 10;
var OUTERITERATIONS = 5;
function compare(a, b) {
if (a.v < b.v)
return -1;
if (a.v > b.v)
return 1;
return 0;
}
function compareValue(a, b) {
return a.v - b.v;
}
var timer = function (name, func) {
var sum = 0;
for (var i = 0; i < INNERITERATIONS; i++) {
populate();
global.gc();
var start = Date.now();
func.call();
var stop = Date.now();
global.gc();
if ((sortarray[0].v !== 1) || (sortarray[1].v !== 2)) {
console.log(sortarray[0], sortarray[1]);
console.log('Not sorted!');
}
sum += (stop - start);
}
if (!(name in sumTime))
sumTime[name] = 0;
sumTime[name] += (sum/10);
console.log('Running ' + name + ' for average ' + (sum / 10) + ' ms');
}
var populate = function () {
sortarray = [];
for (var i = ARRAYCOUNT; i > 0; i--) {
var test = {
v: i
}
sortarray.push(test);
}
}
for (var i = 0; i < OUTERITERATIONS; i++) {
timer('compare', function () {
sortarray.sort(compare);
})
timer('compareValue', function () {
sortarray.sort(compareValue);
})
timer('async', function () {
async.sortBy(sortarray, function (entry, callback) {
callback(null, entry.v);
}, function (err, results) {
sortarray = results;
});
})
timer('underscore', function () {
sortarray = _.sortBy(sortarray, 'v');
});
}
console.log('-----------');
_.keys(sumTime).sort(function(a,b) { return sumTime[a]-sumTime[b]}).forEach(function(type) {
console.log(type+' '+(sumTime[type]/OUTERITERATIONS).toFixed(2));
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment