var arr = [];
for (var i = 0; i < 12345; i++) {
arr[i] = i;
}
function reduceFilterMap(filterSelector, valueSelector) {
return [
(previousValue, currentValue, currentIndex) => {
const shouldBeAdded = filterSelector(currentValue, currentIndex);
if (shouldBeAdded) {
previousValue.push(valueSelector(currentValue, currentIndex));
}
return previousValue;
},
[],
];
}
arr.filter(v => v % 2).map(v => v * 2);
arr.reduce(reduceFilterMap(v => v % 2, v => v * 2))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
filter.map | |
reduce |
Test name | Executions per second |
---|---|
filter.map | 12177.8 Ops/sec |
reduce | 6040.9 Ops/sec |
Let's dive into the explanation of the benchmark.
Benchmark Definition JSON
The benchmark definition is a JavaScript code that represents a microbenchmark. In this case, there are two benchmark definitions:
arr.filter(v => v % 2).map(v => v * 2);
arr.reduce(...reduceFilterMap(v => v % 2, v => v * 2))
These benchmarks test the performance of filtering and mapping operations on an array.
Options Compared
The two benchmark definitions compare different approaches to perform filtering and mapping:
Array.prototype.filter()
followed by Array.prototype.map()
. This approach is straightforward but might be slower due to the overhead of function calls.Array.prototype.reduce()
, which is a more efficient approach that combines filtering and mapping into a single operation.Pros and Cons
Filtering and Mapping
Pros:
Cons:
Reduce with Filter
Pros:
Cons:
Library and Syntax
In this benchmark, we're using standard JavaScript libraries and syntax. There are no specific libraries or frameworks mentioned in the benchmark definition.
However, if we look at the reduceFilterMap
function in the script preparation code, it's not a part of the standard JavaScript library. This function is likely a custom implementation for testing purposes.
Special JS Feature or Syntax
There are no special JS features or syntax used in this benchmark. The code follows standard JavaScript syntax and conventions.
Other Alternatives
If you're interested in alternative approaches to filtering and mapping, here are some options:
Array.prototype.filter()
followed by a forEach()
loopArray.prototype.map()
with an iterator (e.g., for...of
loop)Keep in mind that the best approach depends on your specific use case, JavaScript engine, and target audience.