$.inArray, _.indexOf, and a simple loop

JavaScript performance comparison

Revision 10 of this test case created

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js">
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    var r;
    var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '11', '12', '33', '44', '55', '66', '77', '88', '99'];
   
    function contains(array, value) {
      var index = -1,
          length = array.length;
   
      while (++index < length) {
        if (array[index] === value) {
          return true;
        }
      }
      return false;
    }
   
        function array_contains( array, value ) {
   
            var index,
                length = array.length;
   
            for ( index = 0; index < length; index++ ) {
                if (array[index] === 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('33', array);
pending…
_.indexOf
r = _.indexOf(array, '33') > -1;
pending…
simple while loop
r = contains(array, '33');
pending…
simple for loop

r = array_contains(array, '33');
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