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); });
arr.filter(function(item){ item.data=someFn(item.id); });
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for | |
map | |
filter |
Test name | Executions per second |
---|---|
foreach | 5817.9 Ops/sec |
for | 2177.7 Ops/sec |
map | 5872.2 Ops/sec |
filter | 5705.6 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
The provided benchmark definition json represents a simple script that creates an array of objects with an id
field and then applies a calculation to this data using four different approaches: forEach
, for
, map
, and filter
. The purpose of this benchmark is to compare the performance of these four methods in updating the data
property of each object.
Options being compared:
forEach
: This method iterates over an array, executing a provided function for each element.for
loop: A traditional loop that uses a variable to keep track of the iteration index.map
: This method creates a new array with the results of applying a provided function to each element in the original array.filter
: Similar to map
, but it only includes elements for which the provided function returns true.Pros and cons of each approach:
forEach
:for
loop:map
:filter
:map
, but only includes elements that pass the test.Library usage:
None of these methods use any external libraries. They are all built-in features of JavaScript.
Special JS feature or syntax:
The provided benchmark definition uses no special features or syntax beyond what's standard in JavaScript.
Now, let's look at some alternatives:
reduce
, which combines multiple array operations into one; using Promise.all
with map
and then
to handle updates sequentially; or even using a more functional programming approach like recursion.Keep in mind that performance differences between these methods can vary depending on the specific use case, data size, and JavaScript environment.