Array unique

JavaScript performance comparison

Revision 13 of this test case created by OhJeez

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/mootools/1.3/mootools-yui-compressed.js">
</script>
<script src="https://raw.github.com/mootools/mootools-more/master/Source/Types/Array.Extras.js">
</script>
<script>
  var array = [],
      i;
  
  for (i = 0; i < 10000; ++i) array[i] = Math.floor(Math.random()*100)+1;
  
  function mootools_unique(arr) {
    var target = [];
    for (var i = 0, a = arr.length; i < a; i++) {
      var obj = arr[i];
      if (target.indexOf(obj) == -1) {
        target.push(obj);
      }
    }
    return target;
  }
</script>
      
<script>
Benchmark.prototype.setup = function() {
  var mu = mootools_unique; // avoid scope lookup penalty in the test itself

};
</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
Using indexOf - O(n2)
array.filter(function(element, index, array) {
  return array.slice(0, index).indexOf(element) == -1;
});
pending…
Using indexOf and ~ - O(n2)
array.filter(function(element, index, array) {
  return !~array.slice(0, index).indexOf(element);
});
pending…
Using a map - O(n)
array.filter(function() {
  var seen = {};
  return function(element, index, array) {
    return !(element in seen) && (seen[element] = 1);
  };
}());
pending…
Using sort and filter - O((n lg n) + n)
array.sort().filter(function(element, index, array) {
  return element !== array[index - 1]
});
pending…
Using better indexOf logic
array.filter(function(element, index, array) {
  return array.indexOf(element, index + 1) < 0;
});
pending…
Using simpler in logic
array.filter(function(element, index, array) {
  return element in this ? false : this[element] = true;
}, {});
pending…
MooTools forEach inlined
mu(array);
pending…
sort + while loop O(log n + n)
array.sort();
var l = array.length;
var res = [];
var p = 0;
while (--l) {
  if (array[l - 1] != array[l]) res[p++] = array[l];
}
pending…
Reduce + indexOf O(n^2)
array.reduce(function(p, c) {
  if (p.indexOf(c) < 0) p.push(c);
  return p;
}, []);
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