I am looking at improving some of our for each loops and created a test benchmark to compare different ways we are using them. The test can be found here.
I was surprised to find out that this code:
function add(val) {
sum += val;
}
values.forEach(add);
performs better than this one.
values.forEach(function(val) {
sum += val;
});
Aren't these exactly the same? What makes the first code snippet faster than the second one?
forEach LoopIt is faster in performance. It is slower than the traditional loop in performance.
Correctly used, while is the fastest, as it can have only one check for every iteration, comparing one $i with another $max variable, and no additional calls before loop (except setting $max) or during loop (except $i++; which is inherently done in any loop statement).
Foreach performance is approximately 6 times slower than FOR / FOREACH performance. The FOR loop without length caching works 3 times slower on lists, comparing to arrays. The FOR loop with length caching works 2 times slower on lists, comparing to arrays.
It's a problem with your test. Your tests are:
values.forEach(add);
and
values.forEach(function(val) {
sum += val;
});
In the second test, you're timing the creation of the function as well as the execution of the forEach
. In the first test, you're not timing the creation of the function; that's done during the setup phase of the test, which isn't timed.
Davin Tryon created a test that creates the functions in both cases:
function add(val) {
sum += val;
}
values.forEach(add);
vs.
values.forEach(function(val) {
sum += val;
});
...in which the difference in performance disappears on some engines, and goes the other way (declaration being slower) on some. (The latter is probably that the engine figures out during the test that it can inline the function, or at least skip some of the steps that it can't skip with a declaration.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With