为什么 forEach 比常规迭代器更受欢迎? [英] Why should forEach be preferred over regular iterators?
问题描述
我正在阅读
由于它们都很快,因此仅出于性能原因选择不太合适的循环方法可以考虑初步优化,除非另有证明.
forEach
与 for..of
相比的主要优点是前者即使在 ES3 中也是 polyfill 并且提供值和索引,而后者更多可读,但应在 ES5 及更低版本中转译.
forEach
具有已知的缺陷,使其在某些可以使用 for
或 for..of
正确处理的情况下不合适:>
回调函数创建新的上下文(可以用箭头函数寻址)
不支持迭代器
不支持生成器
yield
和async..await
没有提供使用
break
提前终止循环的正确方法
I was reading airbnb javascript guide. There is a particular statement, that says:
Don’t use iterators. Prefer JavaScript’s higher-order functions instead of loops like for-in or for-of.
The reason they give for the above statement is:
This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.
I could not differentiate between the two coding practices given:
const numbers = [1, 2, 3, 4, 5];
// bad
let sum = 0;
for (let num of numbers) {
sum += num;
}
sum === 15;
// good
let sum = 0;
numbers.forEach((num) => {
sum += num;
});
sum === 15;
Could anyone explain, why should forEach
be preferred over regular for
loop? How does it really make a difference? Are there any side effects of using the regular iterators
?
This reasoning in Airbnb style guide applies to array methods that are used for immutability, which are filter
, map
, reduce
, etc. but not forEach
:
This enforces our immutable rule. Dealing with pure functions that return values is easier to reason about than side effects.
So the comparison is more like:
// bad
let sum = 0;
for (let num of numbers) {
sum += num;
}
sum === 15;
// bad
let sum = 0;
numbers.forEach((num) => {
sum += num;
});
sum === 15;
// good
const sum = numbers.reduce((num, sum) => sum += num, 0);
sum === 15;
Generally, for > forEach > for..of > for..in
in terms of performance. This relationship is uniform in almost all engines but may vary for different array lengths.
forEach
is the one that was significantly improved in latest Chrome/V8 (almost twice, based on this synthetic test):
Since all of them are fast, choosing less appropriate loop method just because of performance reasons can be considered preliminary optimization, unless proven otherwise.
The main benefits of forEach
in comparison with for..of
is that the former be polyfilled even in ES3 and provides both value and index, while the latter is more readable but should be transpiled in ES5 and lower.
forEach
has known pitfalls that make it unsuitable in some situations that can be properly handled with for
or for..of
:
callback function creates new context (can be addressed with arrow function)
doesn't support iterators
doesn't support generator
yield
andasync..await
doesn't provide a proper way to terminate a loop early with
break
这篇关于为什么 forEach 比常规迭代器更受欢迎?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!