Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 would suspect they'd be O(1) (constant time) but would love to see any references or tests that might exist.

like image 262
haknick Avatar asked May 16 '11 00:05

haknick


People also ask

What is the time complexity of hasOwnProperty?

The last built-in method we will discuss for objects is hasOwnProperty. This method has an O(1) or constant time and works by returning true or false depending on if the key is present in the object.

What is the difference between in and hasOwnProperty?

Both also support ES6 symbols. So what's the difference between the two? The key difference is that in will return true for inherited properties, whereas hasOwnProperty() will return false for inherited properties.

What is hasOwnProperty?

The hasOwnProperty() method returns true if the specified property is a direct property of the object — even if the value is null or undefined . The method returns false if the property is inherited, or has not been declared at all.

Which of these is the correct Big O expression for 1 2 3 n?

The answer is O(1) if you use the formula for summation directly. Save this answer. Show activity on this post. the addition is called n times, so the whole code has a time complexity of O(1) * n = O(n).


1 Answers

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

like image 159
alex Avatar answered Oct 20 '22 08:10

alex