问题
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 supportsletvariables. Back before ESv6, when you declared avarvariable, 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