find element in obj vs array

JavaScript performance comparison

Revision 12 of this test case created

Info

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?

And in case the compiler's much too clever, test random access.

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 unknown unknown
Test Ops/sec
find in array (1)
n=Math.floor((Math.random()*1000));
if (in_array(1, arr)) {
  count++;
}
pending…
find in array (random)
n=Math.floor((Math.random()*1000));
if (in_array(500, arr)) {
  count++;
}
pending…
find in array (999)
n=Math.floor((Math.random()*1000));
if (in_array(999, arr)) {
  count++;
}
pending…
find in obj (1)
n=Math.floor((Math.random()*1000));
if (obj[1]) {
  count++;
}
pending…
find in obj (random)
n=Math.floor((Math.random()*1000));
if (obj[n]) {
  count++;
}
pending…
find in obj (999)
n=Math.floor((Math.random()*1000));
if (obj[999]) {
  count++;
}
pending…
indexOf in arr(1)
n=Math.floor((Math.random()*1000));
if (arr.indexOf(n) != -1) {
  count++;
}
pending…
indexOf in arr(random)
n=Math.floor((Math.random()*1000));
if (arr.indexOf(500) != -1) {
  count++;
}
pending…
indexOf in arr(999)
n=Math.floor((Math.random()*1000));
if (arr.indexOf(999) != -1) {
  count++;
}
pending…
build lookup index
n=Math.floor((Math.random()*1000));
for (var i = 0; i < 1000; i++) {
  obj[i] = arr[i];
}
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