jQuery.inArray vs indexOf vs custom (v8)

Revision 8 of this benchmark created on


Preparation HTML

<script src="http://code.jquery.com/jquery-1.10.1.min.js">
</script>

Setup

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'];
    
    array_list.sort();
    
    function custom_search(arr, val) {
      for (var i = 0, len = arr.length; i < len; i++) {
        if (arr[i] == val) return i;
      }
      return -1;
    }
    
    function custom_search_v2(arr, val) {
    
      var i = arr.length;
      while(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;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
indexOf first
array_list.indexOf('this is a string')
ready
indexOf last
array_list.indexOf('random strings')
ready
$.inArray first
jQuery.inArray('this is a string', array_list)
ready
$.inArray last
jQuery.inArray('random strings', array_list)
ready
custom first
custom_search(array_list, 'this is a string');
ready
custom last
custom_search(array_list, 'random strings');
ready
binary first
binarySearch(array_list, 'this is a string');
ready
binary last
binarySearch(array_list, 'random strings');
ready
custom first v2
custom_search_v2(array_list, 'this is a string');
ready
custom last v1
custom_search_v2(array_list, 'random strings');
ready

Revisions

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