Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript foreach loop performance

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?

like image 739
GETah Avatar asked Jan 22 '15 09:01

GETah


People also ask

Is forEach faster than for loop JavaScript?

forEach LoopIt is faster in performance. It is slower than the traditional loop in performance.

Which is the fastest while for forEach () for of?

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

Is forEach slower than for?

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.


1 Answers

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

enter image description here

like image 149
T.J. Crowder Avatar answered Dec 03 '22 16:12

T.J. Crowder