var arr = [];
for (var i = 0; i < 50000; i++) {
arr.push(i);
}
var objForEach = {};
arr.forEach(item => {
objForEach[item] = { exists: true };
});
var objReduce = arr.reduce((acc, item) => {
acc[item] = { exists: true };
return acc;
}, {});
var objFor = {};
for (var j = 0; j < arr.length; j++) {
var item = arr[j];
objFor[item] = { exists: true };
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
forEach | |
reduce | |
for |
Test name | Executions per second |
---|---|
forEach | 86.2 Ops/sec |
reduce | 106.1 Ops/sec |
for | 17.0 Ops/sec |
Let's dive into the benchmark.
What is being tested?
The benchmark is testing three different ways to fill an object (objForEach
, objReduce
, and objFor
) with data from an array (arr
) of 50,000 items. The goal is to compare the performance (speed) of these three approaches: using forEach
, reduce
, and a traditional for
loop.
What options are compared?
The benchmark compares three options:
forEach
method on the array to iterate over its elements and add them to an object.reduce
method on the array to accumulate an object with the desired data.for
loop to iterate over the array's elements and add them to an object.Pros/Cons of each approach:
forEach
or for
loops for simple use cases.forEach
for very large datasets and is easy to read. It's also a traditional looping approach which many developers are familiar with.forEach
or reduce
, and can lead to more boilerplate code.Other considerations:
=>
) in the forEach
test case. This is a modern JavaScript feature (introduced with ES6) that allows for concise function definitions.Other alternatives:
You could also compare other methods such as using a map
function, or even using a library like Lodash's each
method if you want to see how they perform in comparison.