jQuery.inArray vs indexOf vs custom

JavaScript performance comparison

Revision 6 of this test case created

Preparation code

<script src="http://code.jquery.com/jquery-1.10.1.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    var array_list = ['this is a string', 'this is not a string', 'here is my string', 'here is not my string', 'hello world', 'not hello world', 'blah', 'blah blah blah', 'this is not some blah', 'here is some more blah', 'would you like some blah?', 'no i would not like some blah.', 'thanks', 'ok', 'random strings'];
   
    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('this is a string')
pending…
indexOf last
array_list.indexOf('random strings')
pending…
$.inArray first
jQuery.inArray('this is a string', array_list)
pending…
$.inArray last
jQuery.inArray('random strings', array_list)
pending…
custom first
custom_search(array_list, 'this is a string');
pending…
custom last
custom_search(array_list, 'random strings');
pending…
binary first
binarySearch(array_list, 'this is a string');
pending…
binary last
binarySearch(array_list, 'random strings');
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