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 开发者_如何学JAVAdoing 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.propwill check if a property is not falsy (notnull,undefined,0,"",false).prop in objchecks whether a property exists in an object (including it's prototype chain)And finally you have
obj.hasOwnProperty('prop')which checks if the object haspropas 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.
加载中,请稍侯......
精彩评论