“in”中Big O表示法的效率是多少? operator或obj.hasOwnProperty(prop)

问题描述:

Mozilla的网站清楚地描述了 hasOwnProperty() 运营商。

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

但是,它没有提供有关其效率的任何实施细节。

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

我怀疑他们是 O(1)(常数时间)但是很想看到任何可能存在的引用或测试。

I would 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() 应该 O(1),因为它是一个键查找,但是它将是特定于实现的。

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

中肯定会更复杂(尽管应该与 hasOwnProperty()如果该对象上存在该属性,则为g oes the the prototype chain,寻找那个属性。这就是为什么经常建议使用 hasOwnProperty()进行迭代,使用对(in)进行迭代。

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 :)