Skip to content

Instantly share code, notes, and snippets.

@lancejpollard
Created January 25, 2013 09:18
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save lancejpollard/4633028 to your computer and use it in GitHub Desktop.
var Benchmark = require('benchmark')
, suite = new Benchmark.Suite();
var options = {
onComplete: function() {
print(this);
}
}
var lowerCase = [
'a', 'b', 'c', 'd', 'e', 'f', 'j', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
];
var upperCase = [
'A', 'B', 'C', 'D', 'E', 'F', 'J', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
];
var sourceArray = lowerCase.concat()
, testArray = lowerCase.concat(upperCase);
suite.add('unique (using Array.prototype.indexOf)', function() {
var source = sourceArray.concat()
, i = testArray.length;
while (i--) {
if (source.indexOf(testArray[i]) === -1)
source.push(testArray[i]);
}
return source;
}, options);
suite.add('unique (using hash to store properties)', function() {
var hash = {}
, i = sourceArray.length;
while (i--) {
hash[sourceArray[i]] = true;
}
i = testArray.length;
while (i--) {
hash[testArray[i]] = true;
}
return Object.keys(hash);
}, options);
suite.run();
function print(result) {
console.log(result.toString() + ' (' + (result.times.period * 1000.0).toFixed(3) + 'ms)');
}
$ node benchmark.js
unique (using Array.prototype.indexOf) x 197,816 ops/sec ±0.76% (102 runs sampled) (0.005ms)
unique (using hash to store properties) x 61,929 ops/sec ±0.80% (98 runs sampled) (0.016ms)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment