Array unique (v3)

Revision 3 of this benchmark created on


Description

@wolframkriesing wondered what the most efficient unique function for Array would be: http://twitter.com/wolframkriesing/status/83847205189980160

Let’s find out!

Preparation HTML

<script src="//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 = [1, 2, 3, 4, 2, 3, 4, 5, 6, 7, 2, 3, 4, 1, 2, 3, 4, 2, 3, 4, 5, 6, 7, 2, 3, 4];
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Using indexOf - O(n2)
array.filter(function(e, i, arr) {
  return arr.slice(0, i).indexOf(e) == -1;
});
ready
Using indexOf and ~ - O(n2)
array.filter(function(e, i, arr) {
  return !~arr.slice(0, i).indexOf(e);
});
ready
Using a map - O(n)
array.filter(function() {
  var seen = {};
  return function(e, i, arr) {
    return !(e in seen) && (seen[e] = 1);
  };
}());
ready
Using sort and filter - O((n lg n) + n)
array.sort().filter(function(e, i, arr) {
  return e !== arr[i - 1]
});
ready
using better indexOf logic
array.filter(function(e, i, arr) {
  return arr.indexOf(e, i + 1) < 0;
});
ready
using simpler "in" logic
array.filter(function(e, i, arr) {
  return e in this ? false : this[e] = true;
}, {});
ready
Moo-More unique
array.unique();
ready

Revisions

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