find element in obj vs array (v4)

Revision 4 of this benchmark created by Rob Edgar on


Description

Looking for elements at the very start of the array gives a false impression, see how the picture changes if they elements are at the end of the array.

But how long does it take to build and object lookup table?

Setup

var obj = {},
        arr = [],
        count = 0;
    for (var i = 0; i < 1000; i++) {
      arr.push(i);
      obj[i] = 1;
    }
    
    
    function in_array(needle, haystack) {
      for (var i = 0, maxi = haystack.length; i < maxi; ++i) {
        if (haystack[i] == needle) {
          return true;
        }
      }
      return false;
    }
    
    function include(needle, haystack) {
      return (haystack.indexOf(needle) != -1);
    }

Test runner

Ready to run.

Testing in
TestOps/sec
find in array (1)
if (in_array(1, arr)) {
  count++;
}
ready
find in array (500)
if (in_array(500, arr)) {
  count++;
}
ready
find in array (999)
if (in_array(999, arr)) {
  count++;
}
ready
find in obj (1)
if (obj[1]) {
  count++;
}
ready
find in obj (500)
if (obj[500]) {
  count++;
}
ready
find in obj (999)
if (obj[999]) {
  count++;
}
ready
indexOf in arr(1)
if (arr.indexOf(1) != -1) {
  count++;
}
ready
indexOf in arr(500)
if (arr.indexOf(500) != -1) {
  count++;
}
ready
indexOf in arr(999)
if (arr.indexOf(999) != -1) {
  count++;
}
ready
build lookup index
for (var i = 0; i < 1000; i++) {
  obj[i] = arr[i];
}
ready

Revisions

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