inArray (v2)

Revision 2 of this benchmark created by Jens Roland on


Description

Checking if an value is present in an array. Of course, the value we are searching for has and the position in the array has costs.

NOTE!! test #4 (the Javascript Array.indexOf() function) is NOT supported in all browsers, so either use one of the other methods or provide a fallback mechanism (see this for a seamless way to do this: http://stackoverflow.com/questions/237104/javascript-array-containsobj/238862#238862)

Preparation HTML

<script>
  function inArray1(needle, haystack) {
   var length = haystack.length;
   for (var i = 0; i < length; i++) {
    if (haystack[i] == needle) return true;
   }
   return false;
  }
  
  function inArray2(needle, haystack) {
   return !!~haystack.join("").indexOf(needle);
  }
  
  function inArray3(needle, haystack) {
   return !haystack.join("").indexOf(needle) == -1
  }
  
  function inArray4(needle, haystack) {
   return !haystack.indexOf(needle) == -1
  }
  
  // From Prototype
  
  function inArray5(needle, haystack) {
   var length = haystack.length;
   for (var i = 0; i < length; i++)
   if (haystack[i] === needle) return i;
   return -1;
  }
  
  // From Prototype, reverse iteration
  
  function inArray6(needle, haystack) {
   var lastindex = haystack.length - 1;
   for (var i = lastindex; i >= 0; i--)
   if (haystack[i] === needle) return i;
   return -1;
  }
  
  
  var arr = [1, 2, 3, 4, 5, 6, 7],
      num = 5;
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
inArray1
inArray1(5, arr);
ready
inArray2
inArray2(5, arr);
ready
inArray3
inArray3(5, arr);
ready
inArray4
inArray4(5, arr);
ready
inArray5
inArray5(5, arr);
ready
inArray6
inArray6(5, arr);
ready

Revisions

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

  • Revision 1: published by frio80 on
  • Revision 2: published by Jens Roland on