最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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

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

I would suspect they'd be O(1) (constant time) but would love to see any references or tests that might exist.

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

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

I would suspect they'd be O(1) (constant time) but would love to see any references or tests that might exist.

Share Improve this question edited May 16, 2011 at 0:41 alex 490k204 gold badges889 silver badges991 bronze badges asked May 16, 2011 at 0:31 haknickhaknick 1,9201 gold badge20 silver badges28 bronze badges 3
  • 2 It's a hashmap I think, so it should be O(1). – alex Commented May 16, 2011 at 0:41
  • It would have only made sense to use some sort of hash since the properties by definition should be unique, but would be nice to check some references on especially how IE implements them. – haknick Commented May 16, 2011 at 0:44
  • I'd say it is probably implementation dependent. I'd crack open the source of your favorite open source implementation. – alex Commented May 16, 2011 at 0:47
Add a comment  | 

3 Answers 3

Reset to default 12

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)

  1. 暂无评论