var arr = [];
for (var i = 0; i < 1000; i++) {
arr[i] = {
'id': i
};
}
function someFn(i) {
return i * 3 * 8;
}
arr.forEach(function (item){
item.data = someFn(item.id);
})
for (var i = 0, len = arr.length; i < len; i++) {
arr[i].data = someFn(arr[i].id);
}
arr.map(function(item){ item.data=someFn(item.id); return item; });
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for | |
map |
Test name | Executions per second |
---|---|
foreach | 9528.1 Ops/sec |
for | 3510.8 Ops/sec |
map | 9226.2 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, compared, and considered.
Benchmark Definition
The website MeasureThat.net provides a JSON representation of a benchmark, which consists of:
arr
with 1000 objects, each containing an id
property. It also defines a function someFn(i)
that takes an i
value and returns i * 3 * 8
.Individual Test Cases
The benchmark has three test cases:
arr.forEach(function (item) {
item.data = someFn(item.id);
});
This test case uses the forEach
method to iterate over the array and update each object's data
property with the result of someFn(item.id)
.
for (var i = 0, len = arr.length; i < len; i++) {
arr[i].data = someFn(arr[i].id);
}
This test case uses a traditional for
loop to iterate over the array and update each object's data
property with the result of someFn(arr[i].id)
.
arr.map(function(item) {
item.data = someFn(item.id);
return item;
});
This test case uses the map
method to create a new array and update each object's data
property with the result of someFn(item.id)
.
Comparison
The benchmark is comparing the performance of these three approaches:
forEach
method to iterate over the array.for
loop to iterate over the array.map
method to create a new array and update each object's property.Pros and Cons
Here are some pros and cons of each approach:
foreach
foreach
due to the way it uses iterators under the hoodLibrary and Special JS Feature
The benchmark does not explicitly use any libraries or special JavaScript features beyond what's considered standard (ECMAScript 2015 and later).
Other Alternatives
If you want to explore other alternatives, here are a few:
forEach
or for
, you could use the reduce()
method to accumulate the results.new Set(arr.map(someFn)).values().toArray()
) might be more efficient.Keep in mind that these alternatives may have different performance characteristics and trade-offs depending on your specific use case.