views:

50

answers:

1

I was curious as of what would be the fastest way to check if a JS object (used as a dictionary) has a given property.

And I was baffled by the results. See for yourself: http://jsperf.com/object-membership-check-speed/6

In Chrome, the in keyword method is 96% slower than the dot syntax. And in Firefox, it's also around 80% slower. IE shows about 50% slower

What the hell? Am I doing something wrong? I imagined the "in" keyword would be optimized, since it doesn't even need to get the value, it just returns a boolean. But I guess I was wrong.

+1  A: 

They are not the same.

  • obj.prop will check if a property is not falsy (not null, undefined, 0, "", false).

  • prop in obj checks whether a property exists in an object (including it's prototype chain)

  • And finally you have obj.hasOwnProperty('prop') which checks if the object has prop as it's own property (can't be an inhereted one).

Example

var obj = { prop: "" };
obj.prototype = { inhereted: true };
if ( obj.prop );            // false
if ( prop in object );      // true
if ( inhereted in object ); // true
if ( obj.hasOwnProperty('prop') );      // true
if ( obj.hasOwnProperty('inhereted') ); // false

I think performance shouldn't be a problem as long as you're not doing millions of checks at a time. If you really want the fastest way though, you can use:

if ( obj.prop != null )

Which checks if the property is not null or undefined. In this form other falsy values like "" or 0 can't interfere, and you're still super performant.

galambalazs
I understand they're not the same. But it's still surprising to see that the simplest (in theory at least) method is the slowest. BTW- I added the hasOwnProperty method to the benchmark to see how it goes, and it's about the same speed of `in`.. a bit surprising as well since it involves getting a property `hasOwnProperty`, and calling that function. While as `in` is just a language construct.
Infinity