GETah
GETah

Reputation: 21409

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?

Upvotes: 6

Views: 1044

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074178

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

Upvotes: 6

Related Questions