Javascript foreach loop performance

I look at some of our improvements for each cycle and created a test test to compare different ways to use them. The test can be found here .

I was surprised to learn that this code:

function add(val) { sum += val; } values.forEach(add); 

works better than this.

  values.forEach(function(val) { sum += val; }); 

Isn't that the same? What makes the first piece of code faster than the second?

+5
source share
1 answer

This is a problem with your test. Your tests:

 values.forEach(add); 

and

 values.forEach(function(val) { sum += val; }); 

In the second test, you determine the creation of a function as well as the execution of forEach . In the first test, you do not define the creation of a function; which runs during the test setup phase, which is not synchronized.

Davin Tryon created a test that creates functions in both cases :

 function add(val) { sum += val; } values.forEach(add); 

against.

 values.forEach(function(val) { sum += val; }); 

... in which the performance difference disappears on some engines and goes the other way (ad slower) on some. (The latter is probably due to the fact that during the test the engine discovers that it can inline the function or at least skip some steps that it cannot skip with the ad.)

enter image description here

+6
source

Source: https://habr.com/ru/post/1211691/


All Articles