Skip to content

Instantly share code, notes, and snippets.

@nevill
Created May 19, 2014 03:48
Show Gist options
  • Save nevill/551c4855e16b0cf108ab to your computer and use it in GitHub Desktop.
Save nevill/551c4855e16b0cf108ab to your computer and use it in GitHub Desktop.
Simpe test on how to strip out duplications from array in Javascript
var _ = require('underscore');
var ObjectID = require('mongodb').ObjectID;
var duplicatedIds = [];
var lengthOfDuplicatedIds = 10;
for (var i = 0; i < lengthOfDuplicatedIds; i++) {
duplicatedIds.push(new ObjectID());
}
var ArrToTest = [];
// change this value to increate the size of testing set
var lengthOfArrayToTest = 8000;
for (var j = 0; j < lengthOfArrayToTest; j++) {
ArrToTest.push(new ObjectID());
}
ArrToTest = _.shuffle(duplicatedIds.concat(ArrToTest).concat(duplicatedIds));
function runTest(func) {
var start = new Date();
func.call();
var end = new Date();
console.log('Using %s: %d milliseconds', func.name, (end.valueOf() - start.valueOf()));
}
function indexOf() {
return _.uniq(ArrToTest);
}
function hash() {
return Object.keys(
ArrToTest.reduce(function(r, value) {
r[value.toString()] = 1;
return r;
}, {})
);
}
runTest(indexOf);
runTest(hash);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment