// 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?
hasOwnProperty() is faster. I realize there are other ways to make the loops faster, like storing lengths in variables.
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.
hasOwnProperty() should be O(1) , as it is a key lookup, but it will be implementation specific.
Conclusion. It turns out that Object. values is about 3.2 times faster than Object.
Object.keys
looks up all own, enumerable properties (oh, and arrays are fast).for in
additionally looks up inherited enumerable properties, not only own onesfor 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With