Array.indexOf vs Object's "in operator (v26)

Revision 26 of this benchmark created on


Description

Testing if access through Array.indexOf or Object's in Operator is faster.

Setup

var guid = (function() {
      function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
          .toString(16)
          .substring(1);
      }
      return function() {
        return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
          s4() + '-' + s4() + s4() + s4();
      };
    })();
    
    var arr = [];
    var obj = {};
    
    for (var i = 0; i < 10000; i++) {
      var g = guid();
      arr.push(g);
      obj[g] = null;
    }
    
    var first = arr[0];
    var last = arr[arr.length - 1];

Test runner

Ready to run.

Testing in
TestOps/sec
Array - Find first element
if (arr.indexOf(first) !== -1) {
  // found
}
ready
Object - Find first element
if (first in obj) {
  // found
}
ready
Array - Find last element
if (arr.indexOf(last) !== -1) {
  // found
}
ready
Object - Find last element
if (last in obj) {
  // found
}
ready
Object - Find first element (typeof)
if (typeof obj[first] !== "undefined") {
  // found
}
ready
Object - Find last element (typeof)
if (typeof obj[last] !== "undefined") {
  // found
}
ready
Object - Find first element (undefined)
if (obj[first] !== void 0) {
  // found
}
ready
Object - Find last element (undefined)
if (obj[last] !== void 0) {
  // found
}
ready

Revisions

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