There is no performance benefit offered by forEach
. In fact, if you look at the source code, the forEach
function actually simply performing for
-in
. For release builds, the performance overhead of this function over simply using for
-in
yourself is immaterial, though for debug builds, it results in an observable performance impact.
The main advantage of forEach
is realized when you are doing functional programming, you can add it to a chain of functional calls, without having to save the prior result into a separate variable that you'd need if you used for
-in
syntax. So, instead of:
let objects = array.map { ... }
.filter { ... }
for object in objects {
...
}
You can instead stay within functional programming patterns:
array.map { ... }
.filter { ... }
.forEach { ... }
The result is functional code that is more concise with less syntactic noise.
FWIW, the documentation for Array, Dictionary, and Sequence all remind us of the limitations introduced by forEach
, namely:
You cannot use a break
or continue
statement to exit the current
call of the body
closure or skip subsequent calls.
Using the return
statement in the body
closure will exit only from
the current call to body
, not from any outer scope, and won't skip
subsequent calls.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…