Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Object.keys faster than hasOwnProperty?

 // hasOwnProperty approach   for (key in obj) {   if (obj.hasOwnProperty(key)) {     value = obj[key];   } }  // Object.keys approach  keys = Object.keys(obj); for (i = 0, l = keys.length; i < l; i++) {   value = obj[keys[i]]; } 

According to jsperf the Object.keys approach is 50%+ faster http://jsperf.com/object-keys-vs-hasownproperty/45

Why is this?

like image 597
menzoic Avatar asked May 19 '15 13:05

menzoic


People also ask

Is hasOwnProperty fast?

hasOwnProperty() is faster. I realize there are other ways to make the loops faster, like storing lengths in variables.

What's the difference between the in operator and the hasOwnProperty method in objects?

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 the time complexity of hasOwnProperty?

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

Are object values slow?

Conclusion. It turns out that Object. values is about 3.2 times faster than Object.


1 Answers

  • Object.keys looks up all own, enumerable properties (oh, and arrays are fast).
  • for in additionally looks up inherited enumerable properties, not only own ones
  • for in + hasOwnProperty additionally tests all looked up properties for whether they are own properties.

Even if there are no inherited enumerable properties, it is still more work to do than not.

like image 73
Bergi Avatar answered Sep 17 '22 21:09

Bergi