array.forEach 比原生迭代运行得更快?如何? [英] array.forEach running faster than native iteration? How?

查看:47
本文介绍了array.forEach 比原生迭代运行得更快?如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://jsperf.com/testing-foreach-vs-for-loop

我的理解是测试用例 2 应该比测试用例 1 运行得更慢——我想看看到底慢了多少.想象一下当我看到它运行得更快时我的惊讶!

It was my understanding that Test Case 2 should run more slowly than Test Case 1 -- I wanted to see how much more slowly. Imagine my surprise when I see it runs more quickly!

这是怎么回事?幕后优化?还是 .forEach 更干净更快?

What's going on here? Behind the scenes optimizaiton? Or is .forEach cleaner AND faster?

在 Windows Server 2008 R2/7 64 位上的 Chrome 18.0.1025.142 32 位中测试

Testing in Chrome 18.0.1025.142 32-bit on Windows Server 2008 R2 / 7 64-bit

推荐答案

for 循环缺少许多迭代优化,例如:

There are many iteration optimizations that your for loop is missing such as:

  • 缓存数组长度
  • 向后迭代
  • 使用 ++counter 代替 counter++

这些是我听说过和使用过的,我相信还有更多.如果没记错的话,向后迭代的 while 循环是所有循环结构中最快的(在大多数浏览器中).

These are the ones that I have heard of and used, I am sure there are more. If memory serves me correct, the backwards iterating while loop is the fastest of all looping structures (in most browsers).

有关示例,请参阅此 jsperf.

postfix vs prefix perf test向后迭代.我找不到使用 +=1 而不是 ++ 的参考,因此我已将其从列表中删除.

links for postfix vs prefix perf test and iterating backwards. I was not able to find my reference for using +=1 instead of ++, so I have removed it from the list.

这篇关于array.forEach 比原生迭代运行得更快?如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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