没有继承属性的for-in与Object.keys forEach [英] for-in vs Object.keys forEach without inherited properties

查看:126
本文介绍了没有继承属性的for-in与Object.keys forEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看具有普通对象的Object.keys + forEachfor-in的性能基准.

I was looking at a perf benchmark of Object.keys + forEach vs for-in with normal objects.

基准表明Object.keys + forEachfor-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 + forEach 41%.

I tried to make another benchmark here doing exactly that. But now the for-in approach is 41% slower than Object.keys + forEach.

更新

以上测试是在Chrome中完成的.再次进行了测试,但是使用Safari,结果却有所不同:Object.keys(..).forEach(..) 34% slower,很奇怪.

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 的情况.

问题:

  • Chrome jsperf结果对 Node.js 是否有意义?
  • 发生了什么事,单一条件如何使for-in方法比 Chrome 中的Object.keys + forEach 41%?
  • Are the jsperf result for Chrome considerable for Node.js?
  • What happened, how come a single conditional made the for-in approach 41% slower than Object.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,它在开发时非常方便,但每次迭代都会添加一个回调,这是一个(相对)冗长的任务.因此,如果您对表演感兴趣,为什么不只使用普通的for循环呢?

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与Object.keys forEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆