开发者

What's the efficiency in Big O notation of the "in" operator or obj.hasOwnProperty(prop)

Mozilla's website clearly describes hasOwnProperty() and the in operator.

However, it does not give any implementation details in regards to their efficiencies.

I wo开发者_运维知识库uld suspect they'd be O(1) (constant time) but would love to see any references or tests that might exist.


To turn my comments into an answer.

hasOwnProperty() should be O(1), as it is a key lookup, but it will be implementation specific.

in will most certainly be more complicated (though should be the same as hasOwnProperty() if the property exists on that object), as it goes up the prototype chain, looking for that property. That is why it is often recommended to use hasOwnProperty() when iterating over object properties with for ( in ).

To find out, inspect the source code of these functions. Use the source, Luke :)


My theory was that in should be faster than hasOwnProperty(). in is a proxy for hasProperty() (per the standard: http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf -- see page 79) which is an internal function that is used extensively throughout the language (and would implicitly be highly optimized). Indeed, the tests show that on average, in is faster.

Link: http://jsfiddle.net/VhhzR/2/

In Firefox, in is decidedly faster. In Chrome, in is only faster when dealing with the complex object (which is puzzling). In Internet Explorer, in takes the lead yet again.

Hopefully this has been helpful :)


I don't imagine it's any different from the object property lookup mechanism, since they do in effect the same thing, difference being hasOwnProperty(prop) only looks in the object itself, whereas o.prop will go down the prototype hierarchy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜