Is there any real benefit for using javascript Array reduce() method?

巧了我就是萌 提交于 2019-11-26 16:41:57

问题


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.

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()?

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

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


回答1:


  • You might want scoping. For example you might want to make callback functions or have references to javascript objects. For more information, see why javascript is not blocked scoped. [edit: modern javascript now supports let variables. Back before ESv6, when you declared a var variable, it got hoisted as if it was written at the top of the function codeblock, so often you had to write bodies of for-loops as functions. This following still applies though:] If you had a function written, might as well use functional style unless it's a significant bottleneck.
  • Your code does not always need to run at full machine speed. You may not even be optimizing code in the bottleneck.
  • Additionally you do not provide your "testing on JSPerf" so we can critique it. For example if you already have a reduction function (or map or forEach function), then I bet the performance would be on-par. Even if not, the testing methodology may be flawed, especially given that many browsers may optimize differently or have different function-call overhead.

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)

(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.)



来源:https://stackoverflow.com/questions/9629431/is-there-any-real-benefit-for-using-javascript-array-reduce-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!