[英]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 根据jsperf,Object.keys方法快50%以上http://jsperf.com/object-keys-vs-hasownproperty/45
Why is this? 为什么是这样?
Object.keys
looks up all own , enumerable properties (oh, and arrays are fast). Object.keys
查找所有自己的 , 可枚举的属性(哦,数组很快)。 for in
additionally looks up inherited enumerable properties, not only own ones for in
另外查找继承的可枚举属性,而不仅仅是自己的属性 for in
+ hasOwnProperty
additionally tests all looked up properties for whether they are own properties. for in
+ hasOwnProperty
另外测试所有查找属性是否属于自己的属性。 Even if there are no inherited enumerable properties, it is still more work to do than not. 即使没有继承的可枚举属性,仍然需要做更多的工作。
Most of the tests in that thread show hasownproperty
to be faster than Object.keys()
. 该线程中的大多数测试显示
hasownproperty
比Object.keys()
更快。 However, for those tests, the amount of properties to cycle through is small (<20 properties). 但是,对于那些测试,循环的属性量很小(<20个属性)。
Wherever the number of object properties is large (no exact number, tests with >100 keys showed Object.keys()
as a clear winner), Object.keys()
beats it. 只要对象属性的数量很大(没有确切的数字,具有> 100个键的测试显示
Object.keys()
作为明显的赢家), Object.keys()
胜过它。
See https://jsperf.com/object-keys-vs-hasownproperty/55 . 请参阅https://jsperf.com/object-keys-vs-hasownproperty/55 。 You can go to the bottom of the page to see all revisions to the testing.
您可以转到页面底部查看测试的所有修订。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.