$.inArray, _.indexOf, lodash.indexOf, a simple loop, and Array#indexOf (v35)

Revision 35 of this benchmark created by Pascal on


Description

Use jQuery, underscore, lodash and native loops to find the index of an array item.

In contrast to the other versions of this benchmark, this one creates an array containing 2000 objects (instead of some small number of integers).

The index to be found is '1337', so most function will not traverse the complete list.

Preparation HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js">
</script>
<script>
  var lodash = _.noConflict();
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js">
</script>

Setup

var r, $ = window.$,
        _ = window._,
        lodash = window.lodash;
    
    var array = [];
    
    // Make Array of Objects, setting pick to Object to be found.
    (function(){
      var max = 2000;
    
      for (var i = 1; i <= max; i++) {
        array.push({name: 'Entry', index: i, value: Math.random()});
      }
    })();
    
    var pick = array[1337];
    pick.name = 'Special';
    
    function contains(array, value) {
      var index = -1,
          length = array.length;
    
      while (++index < length) {
        if (array[index] === value) {
          return true;
        }
      }
      return false;
    }
    
    function contains2(array, value) {
      for (var i = 0, m = array.length; i < m; i++) {
        if (array[i] === value) {
          return true;
        }
      }
      return false;
    }
    
    function contains3(array, value) {
      for (var i = 0, l = -1 + array.length, m=Math.floor((l+1)/2); i <= m; i++) { 
        if (array[i] === value) return true;
        else if (array[(l-i)] === value) return true;    
      }
      return false;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
$.inArray
r = $.inArray(87, array) > -1;
ready
_.indexOf
r = _.indexOf(array, 87) > -1;
ready
Simple loop
r = contains(array, 87);
ready
Array#indexOf
r = array.indexOf(87) > -1;
ready
lodash.indexOf
r = lodash.indexOf(array, 87) > -1;
ready
lodash.contains
r = lodash.contains(array, 87);
ready
Simpler loop
r = contains2(array, 87);
ready
Simpler loop (halved)
r = contains3(array, 87);
ready

Revisions

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