for-in vs Object.key forEach没有继承属性 [英] for-in vs Object.key forEach without inherited properties
问题描述
我正在寻找 Object.keys
+ forEach
vs 的性能指标-in
包含普通对象。
I was looking at a perf benchmark of Object.keys
+ forEach
vs for-in
with normal objects.
这个基准测试显示 Object.keys
+ forEach
是<强>比 for-in
方法慢<62%。但是,如果您不想获取继承的属性,该怎么办? for-in
包含所有非本地继承对象,因此我们必须使用 hasOwnProperty 进行检查。
This benchmark shows that Object.keys
+ forEach
is 62% slower than the for-in
approach. But what if you don't want to get the inherited properties? for-in
includes all non-native inherited objects, so we'll have to use hasOwnProperty to check.
我试图在这里制作另一个 基准 正是这样做的。但现在 for-in
方法比 Object.keys
+ <慢41% code> forEach 。
I tried to make another benchmark here doing exactly that. But now the for-in
approach is 41% slower than Object.keys
+ forEach
.
update
上述测试是在Chrome中完成的。再次测试它但是我得到了不同的结果: Object.keys(..)。forEach(..)慢34%
,奇数。
The above test was done in Chrome. Tested it again but with Safari and I'm getting different results: Object.keys(..).forEach(..) 34% slower
, odd.
注意:我进行基准测试的原因是检查它与 Node.js 的关系。
问题:
- 是
jsperf
Chrome 的结果相当于 Node.js ? - 发生了什么,为什么单个条件使
for-in
接近慢41%比Object.keys
Chrome 中的+forEach
?
- Are the
jsperf
result for Chrome considerable for Node.js? - What happened, how come a single conditional made the
for-in
approach 41% slower thanObject.keys
+forEach
in Chrome?
推荐答案
node.js使用V8,虽然我猜它与Chrome中的当前版本不一样,但我想这是节点在该主题上表现的一个很好的指标。
node.js uses V8, although I guess it's not the same as the current version in Chrome, but I guess it's a good indicator of node's performances on the subject.
其次,你正在使用 forEach
,这在开发时非常方便,但每次迭代都会添加一个回调,这是一个(相对)长度任务。所以,如果你对表演感兴趣,你为什么不用正常的进行
循环?
Secondarily, you're using forEach
, which is quite handy when developing but adds a callback for every iteration, and that's a (relatively) lenghty task. So, if you're interested in performances, why don't you just use a normal for
loop?
for (var i = 0, keys = Object.keys(object); i < keys.length; i++) {
// ...
}
这样可以获得最佳性能,也可以解决Safari中的速度问题。
This yields the best performances you can get, solving your speed problems in Safari too.
简而言之:它不是有条件的,而是对 hasOwnProperty
的调用会产生影响。你在每次迭代时都在进行函数调用,这就是为什么 for ... in
变慢了。
In short: it's not the conditional, it's the call to hasOwnProperty
that makes a difference. You're doing a function call at every iteration, so that's why for...in
becomes slower.
这篇关于for-in vs Object.key forEach没有继承属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!