是否有使用JavaScript数组减少()方法的任何实际的好处? [英] Is there any real benefit for using javascript Array reduce() method?

查看:130
本文介绍了是否有使用JavaScript数组减少()方法的任何实际的好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在减少()方法的大多数用例可以用一个for循环被轻易改写。和测试上JSPerf表明,减少()通常是60%-75较慢%,取决于每一次迭代中执行的操作。

Most use cases of the reduce() method can be easily rewritten with a for loop. And testing on JSPerf shows that reduce() is usually 60%-75% slower, depending on the operations performed inside each iteration.

有没有真正的理由使用减少(),那么,不是能够编写code在功能性风格等?如果你可以通过写只是多一点code,60%的性能提升,为什么你会永远使用减少()?

Is there any real reason to use reduce() then, other than being able to write code in a 'functional style'? If you can have a 60% performance gain by writing just a little bit more code, why would you ever use reduce()?

编辑:其实,其他的功能的方法,如的forEach()和map()都显示出相似的性能,比简单的慢至少60%的for循环

In fact, other functional methods like forEach() and map() all show similar performance, being at least 60% slower than simple for loops.

下面是对JSPerf测试的链接(与函数调用): forloop VS的forEach

Here's a link to the JSPerf test (with function calls): forloop vs forEach

推荐答案


  • 您可能希望作用域。例如,您可能想使回调函数或有JavaScript对象的引用。欲了解更多信息,请参阅为什么要使用JavaScript不堵塞范围。

  • 您$​​ C $ C并不总是需要全机的速度运行。你甚至可能不会被优化code中的瓶颈。

  • 此外你没有提供你的测试上JSPerf所以我们可以批判它。例如,如果你已经有了一个减弱功能(或地图或功能的forEach),那么我敢打赌,性能将是对标准杆。即使没有,测试方法可能存在缺陷,特别是考虑到许多浏览器可以优化不同或有不同的函数调用的开销。

旁注:这是语法之间的有效性能比较,但一个无效的性能对比的时候语法不是眼下的问题:

sidenote: this is a valid performance comparison between syntax, but an invalid performance comparison in when syntax is not the question at hand:

myArray.map(function(x){return x+1})

// ...versus...

for(var i=0; i<myArray.length; i++) {
    myArray[i] = myArray[i]+1;
}

这将是一个有效的性能对比:

This would be a valid performance comparison:

myArray.forEach(function(x){return x+1})

// ...versus...

var plusOne = function(x){return x+1};
for(var i=0; i<myArray.length; i++) {
    plusOne(myArray[i]);
}

// (may need a side-effect if the compiler is smart enough to optimize this)

(另外,在回答您的编辑: .forEach() .MAP()提供更清晰,并避免显式循环,需要 INT I = 0; I&LT; array.length。我++ 参数)

(Also in reply to your edit: .forEach() and .map() provide much more clarity, and avoid the need for explicit loop int i=0; i<array.length; i++ arguments.)

这篇关于是否有使用JavaScript数组减少()方法的任何实际的好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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