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 apparently I was plain wrong.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With