find element in obj vs array

JavaScript performance comparison

Revision 2 of this test case created by

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  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);
  }

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
indexOf in arr(5)
if (include(5, arr)) {
  count++;
}
pending…
indexOf in arr(9)
if (include(9, arr)) {
  count++;
}
pending…
find in array (1)
if (in_array(1, arr)) {
  count++;
}
pending…
find in array (5)
if (in_array(5, arr)) {
  count++;
}
pending…
find in array (9)
if (in_array(9, arr)) {
  count++;
}
pending…
find in obj (1)
if (obj[1]) {
  count++;
}
pending…
find in obj (5)
if (obj[5]) {
  count++;
}
pending…
find in obj (9)
if (obj[9]) {
  count++;
}
pending…
indexOf in arr(1)
if (include(1, arr)) {
  count++;
}
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.

2 Comments

Jörn commented :

Chrome 18.0.1025 is actually Chrome Mobile (first non-beta) on a Samsung Galaxy S3

Mitch Golden commented :

I don't trust this benchmark. I am afraid that the JIT compilers are optimising the calculation by moving the entire computation outside of the loop, thereby defeating the test. The reason I think this is that (a) it's just so fast, and (b) in some cases it seems not to depend on 1 vs 5 vs 9 (and anyway all of those numbers are too small).