Difference between two arrays with native javascript or underscore or jquery (v16)

Revision 16 of this benchmark created on


Description

We want to find out the differences between two sorted arrays. Eg : [1, 2, 3, 4, 5] and [3, 4, 5] should return [1, 2]

Much larger arrays are used in practice.

Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<script src="https://rawgithub.com/lodash/lodash/2.4.1/dist/lodash.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>

Setup

var foo = [], bar = [], num;
    for(var i=0;i<10000;i++) {
      num = Math.floor(Math.random() * 1000000);
      foo.push(num);
      if (Math.random() > 0.5) num = Math.floor(Math.random() * 1000000);
      bar.push(num);
    }
    foo.sort();
    bar.sort();

Test runner

Ready to run.

Testing in
TestOps/sec
Native javascript
var baz = [];

foo.forEach(function(key) {
  if (-1 === bar.indexOf(key)) {
    baz.push(key);
  }
}, this);
ready
jQuery
var baz = [];

$.each(foo, function(key) {
  if (-1 === bar.indexOf(key)) {
    baz.push(key);
  }
});
ready
LoDash
var baz = _.difference(foo, bar);
ready
angular
var baz = [];

angular.forEach(foo, function(key) {
  if (-1 === bar.indexOf(key)) {
    baz.push(key);
  }
});
ready
Native JS no function calls
var baz = [];

for (var i = foo.length - 1; i >= 0; i--) {
  var key = foo[i];
  if (-1 === bar.indexOf(key)) {
    baz.push(key);
  }
}
ready
Hash
var baz = [], i, hash = {};
for(i = bar.length - 1; i >= 0; i--) {
 hash[bar[i]] = true;
}
for(i = foo.length - 1; i >= 0; i--) {
 if (hash[foo[i]] !== true) baz.push(foo[i]);
}
ready
Sort
var i, j, len, baz = [], bari, fooi;

j = foo.length - 1;
fooi = foo[j];
for(i = bar.length - 1; i>=0 && j>=0; i--) {
 bari = bar[i];
 while(fooi > bari) {
  j--;
  fooi = foo[j];
 }
 if (fooi !== bari) baz.push(bari);
}
for(j=0;j<=i;j++) {
 baz.push(bar[j]);
}
ready

Revisions

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