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.
3 Answers
Reset to default 12To 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.
O(1)
. – alex Commented May 16, 2011 at 0:41