hasOwnProperty vs in vs undefined (v57)

Revision 57 of this benchmark created on


Setup

var obj = {
      one: true,
      two: false,
      action: {},
      three: true,
      four: true
    };
    //not caching the keys array makes this already poor method even slower
    //can use Object.keys instead of Object.getOwnPropertyNames
    var keys = Object.getOwnPropertyNames(obj);
    var i = 0;
    var y = 0;

Test runner

Ready to run.

Testing in
TestOps/sec
hasOwnProperty
//this will only return true if the object itself (not its prototype chain) has a property
i = 1000;
y = 0;
while (i--) {
  if (obj.hasOwnProperty("actions")) {
    y++;
  }
  if (obj.hasOwnProperty("foo")) {
    y++;
  }
}
ready
in
//this returns true in all cases that a property is set on an object or up its prototype chain
i = 1000;
y = 0;
while (i--) {
  if ("actions" in obj) {
    y++;
  }
  if ("foo" in obj) {
    y++;
  }
}
ready
typeof 'undefined'
//this will also return false if a property is set to undefined
//using a string variable with the value of 'undefined' instead is significantly slower
i = 1000;
y = 0;
while (i--) {
  if (typeof obj.actions !== 'undefined') {
    y++;
  }
  if (typeof obj.foo !== 'undefined') {
    y++;
  }
}
ready
boolean coercion
//this will also return false if the property is set to any falsy value (empty string, 0, false, undefined, null, NaN)
i = 1000;
y = 0;
while (i--) {
  if (obj.actions) {
    y++;
  }
  if (obj.foo) {
    y++;
  }
}
ready
in keys array
//this only gets slower as more properties are added to an object
i = 1000;
y = 0;
while (i--) {
  if (keys.indexOf('actions') !== -1) {
    y++;
  }
  if (keys.indexOf('foo') !== -1) {
    y++;
  }
}
ready
equals undefined
//this will also return false if a property is set to undefined
i = 1000;
y = 0;
while (i--) {
  if (obj.actions !== undefined) {
    y++;
  }
  if (obj.foo !== undefined) {
    y++;
  }
}
ready

Revisions

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