Unique array (v2)

Revision 2 of this benchmark created on


Setup

function createTestArray (iterations) {
      var arr = [];
      var i = 0;
  
      for (loop = 0; loop < iterations; loop++) {
          var random = Math.random();
          random = random.toString();
          random = random.substr(2);
  
          arr.push(random);
  
          // 1/3 of times, add a duplicate element
          if (i++ === 3) {
              // reset i
              i = 0;
              arr.push(random);
          }
      }
      return arr;
  }
  
  var testArray = createTestArray(500);

Test runner

Ready to run.

Testing in
TestOps/sec
Hash sieving
var obj = {};
var deduped = [];
testArray.forEach(function (el) {
    obj[el] = el;
});

for (var propt in obj) {
    deduped.push(obj[propt]);
}
ready
IndexOf
var deduped = [];
testArray.forEach(function (el) {
    if (deduped.indexOf(el) === -1) {
        deduped.push(el);
    }
});
ready
array.filter
var string = {};
var deduped = testArray.filter(function(item) {
    // do JSON.stringify for ObjectId
    return string.hasOwnProperty(JSON.stringify(item)) ? false : (string[JSON.stringify(item)] = true);
});
ready
Fast Algorithm
Array.prototype.unique = function() {
    var o = {}, i, l = this.length, r = [];
    for(i=0; i<l;i+=1) o[this[i]] = this[i];
    for(i in o) r.push(o[i]);
    return r;
};
testArray.unique();
ready
Fast Algorithm Optimized
Array.prototype.unique = function () {
    var o = {},
        i,
        l = this.length,
        r = [];

    var distinctItems = Object.keys(this.reduce(function (r, v) { return r[v] = 1, r; }, {})).length;

    if (distinctItems == l)
        return array;

    for (i = 0; i < l; i += 1)
        o[this[i]] = this[i];

    for (i in o)
        r.push(o[i]);

    return r;
};
testArray.unique();
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.