array.filter.unique vs new set

JavaScript performance comparison

Revision 5 of this test case created by

Preparation code

<script src="https://rawcdn.githack.com/lodash/lodash/4.17.11-npm/lodash.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
      
<script>
Benchmark.prototype.setup = function() {
  let array = [];
  
  for (let i = 0; i < 100000; i++) {
    array.push(Math.floor(Math.random() * 100));
  }
  
  function uniqueArray1( ar ) {
    var j = {};
  
    ar.forEach( function(v) {
      j[v+ '::' + typeof v] = v;
    });
  
    return Object.keys(j).map(function(v){
      return j[v];
    });
  } 
  function uniqueArray2(arr) {
      var a = [];
      for (var i=0, l=arr.length; i<l; i++)
          if (a.indexOf(arr[i]) === -1 && arr[i] !== '')
              a.push(arr[i]);
      return a;
  }
  
  function sortUnique(arr) {
      arr.sort();
      var last_i;
      for (var i=0;i<arr.length;i++)
          if ((last_i = arr.lastIndexOf(arr[i])) !== i)
              arr.splice(i+1, last_i-i);
      return arr;
  }
  
  // unused:
  function toUnique(a, b, c) { //array,placeholder,placeholder
    b = a.length;
    while (c = --b)
      while (c--) a[b] !== a[c] || a.splice(c, 1);
    return a // not needed ;)
  }
  
  function protoUnique2(arr) {
      var o = {}, a = []
      for (var i = 0; i < arr.length; i++) o[arr[i]] = 1
      for (var e in o) a.push(e)
      return a
  }
  function getUnique(arr){
       var u = {}, a = [];
       for(var i = 0, l = arr.length; i < l; ++i){
          if(u.hasOwnProperty(arr[i])) {
             continue;
          }
          a.push(arr[i]);
          u[arr[i]] = 1;
       }
       return a;
    }

};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
new set
[...new Set(array)]
pending…
proto unique 2
protoUnique2(array)
pending…
underscorejs uniq
_.uniq(array)
pending…
prototype unique
uniqueArray1(array);
pending…
jQuery grep
$.grep(array, (v, k) => $.inArray(v, array) === k);
pending…
nonfilter indexOf
uniqueArray2(array);
pending…
reduce
array.reduce((acc, curr) => acc.indexOf(curr) > -1 ? acc : [...acc, curr], [])
pending…
sort unique
sortUnique(array);
pending…
array.from new set
Array.from(new Set(array))
pending…
Rafael's arr.getUnique
getUnique(array)
pending…
array unique
array.filter((v, i, a) => a.indexOf(v) === i);
pending…

Compare results of other browsers

Revisions

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

0 Comments