Node.js "forEach", "map" and "reduce" Overhead

This post compares the performance of the JavaScript forEach, map and reduce functions with that of the for loop. It is firmly in the microbenchmark category and should be treated as such. Unless you are working with very large arrays any performance gains will be negligible.

Benchmark Results

Average time from 22 repetitions with the highest and lowest result removed:

1M elementsforEachmapreduce
function16 ms18 ms19 ms
for loop3 ms6 ms3 ms
10M elements 
function246 ms150 ms157 ms
for loop31 ms49 ms31 ms
100M elements 
function3093 ms1565 ms2385 ms
for loop309 ms485 ms310 ms

Test environment:

  • Node.js v12 LTS
  • Debian GNU/Linux (Sid)
  • Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz

Code Being Compared

Complete code available here.

forEach

let r = 0;

data.forEach((item) => {
    r += item.value;
});

return r;
let r = 0;

for (let i = 0; i < data.length; i += 1) {
    r += data[i].value;
}

return r;

map

const r = data.map((item) => item.value);

return r.length;
const r = data.slice();

for (let i = 0; i < data.length; i += 1) {
    r[i] = data[i].value;
}

return r.length;

reduce

const r = data.reduce((i, item) => i + item.value, 0);

return r;
let r = 0;

for (let i = 0; i < data.length; i += 1) {
    r += data[i].value;
}

return r;

Observations

Arrays are fast. :)

Allocating 100 million objects caused a "JavaScript heap out of memory" error with default settings, requiring use of --max_old_space_size option.

In the for loop version of the map function, initialising r with an empty array an using push() resulted in significant reduction in performance - so much so that it became similar to map(). Initialising with new Array(data.length) was except for 100M test where it became slower than map(). Initialising with data.slice() proved the fastest.

Running the tests with the --trace_gc option was interesting because it showed that the functional code was causing many more allocations. The for loop equivalent of reduce() did not trigger any garbage collection.