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

JavaScript performance comparison

Revision 35 of this test case created by Pascal

Info

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 code

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js">
</script>
<script>
  var lodash = _.noConflict();
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    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;
    }
};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
$.inArray
r = $.inArray(87, array) > -1;
pending…
_.indexOf
r = _.indexOf(array, 87) > -1;
pending…
Simple loop
r = contains(array, 87);
pending…
Array#indexOf
r = array.indexOf(87) > -1;
pending…
lodash.indexOf
r = lodash.indexOf(array, 87) > -1;
pending…
lodash.contains
r = lodash.contains(array, 87);
pending…
Simpler loop
r = contains2(array, 87);
pending…
Simpler loop (halved)
r = contains3(array, 87);
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. Here’s a list of current revisions for this page:

0 comments

Add a comment