jQuery.inArray vs indexOf vs custom

JavaScript performance comparison

Revision 4 of this test case created

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    var array_list = [];
    for (var i = 0; i < 1000; i++) {
      array_list[i] = i;
    }
   
    function custom_search(arr, val) {
      for (var i = 0, len = arr.length; i < len; i++) {
        if (arr[i] == val) return i;
      }
      return -1;
    }
   
    function binarySearch(a, value) {
        lo = 0;
        hi = a.length - 1;
        while (lo <= hi) {
            var mid = Math.floor((lo+hi)/2);
            if (a[mid] > value)
                hi = mid - 1;
            else if (a[mid] < value)
                lo = mid + 1;
            else
                return mid;
        }
        return -1;
    }
};
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
indexOf first
array_list.indexOf(0)
pending…
indexOf last
array_list.indexOf(999)
pending…
$.inArray first
jQuery.inArray(0, array_list)
pending…
$.inArray last
jQuery.inArray(999, array_list)
pending…
custom first
custom_search(array_list, 0);
pending…
custom last
custom_search(array_list, 999);
pending…
binary first
binarySearch(array_list, 0);
pending…
binary last
binarySearch(array_list, 999);
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