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

Revision 4 of this benchmark created by Michael on


Description

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

Preparation HTML

<script src="//underscorejs.org/underscore-min.js"></script><script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Setup

var foo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30];
    
    var bar = [1, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 24, 26, 27, 28, 29, 30];

Test runner

Ready to run.

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

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

bar.forEach(function(key) {
  bar2[key] = true;
}, this);

foo.forEach(function(key) {
    if (!bar2[key]) {
        baz.push(key);
    }
}, this);
ready
jQuery
var baz = [];

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

Revisions

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