a=[];
for(i=0;i<1000;i++) a.push(Number(i)/1000);
var filtering=x=>(x*114514)%1>0.5;
var mapping=x=>x+0.1919;
var reducing=(acc,x)=>{
if((x*114514)%1>0.5) acc.push(x+0.1919);
return acc;
}
a.filter(filtering).map(mapping);
a.reduce(reducing,[]);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
map-filter | |
reduce |
Test name | Executions per second |
---|---|
map-filter | 39927.4 Ops/sec |
reduce | 59824.3 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The provided JSON represents a JavaScript microbenchmark that compares two approaches: filter-map
and reduce
. The benchmark is modified to switch the order of operations, which makes it a variation of the original "map-filter vs reduce" benchmark.
Script Preparation Code
The script preparation code defines three functions:
filtering(x)
: takes an input x
, multiplies it by 114514, and checks if the result is greater than 0.5 modulo 1 (i.e., a non-integer value). If true, returns whether the original value plus 0.1919 is greater than 0.5.mapping(x)
: takes an input x
and returns the result of adding 0.1919 to it.reducing(acc, x)
: accumulates values in acc
, pushing new values when the filtering condition is met.Html Preparation Code
There is no HTML preparation code provided, which means that the benchmark does not take into account any DOM-related overhead or asynchronous operations.
Options Compared
The two options being compared are:
Array.prototype.filter()
to filter out elements that don't meet the filtering condition, followed by Array.prototype.map()
to apply the mapping function to the remaining elements.Array.prototype.reduce()
to accumulate values in an accumulator array, applying the reduction function to each element in turn.Pros and Cons
filter()
and map()
methods.filter()
and map()
method calls.Library: Lodash
The reduce
option uses the reduce()
method from the Lodash library. This is a popular utility library that provides additional functional programming helpers, including reduce()
. The use of Lodash here allows for a more concise implementation of the reduction function.
Special JS Feature or Syntax
There are no special JavaScript features or syntax being used in this benchmark.
Other Considerations
The benchmark measures the number of executions per second (ExecutionsPerSecond) for each browser, which provides a relative performance comparison. However, keep in mind that this measurement can be influenced by various factors, such as:
Alternatives
If you're interested in exploring alternative approaches or libraries, here are some options to consider:
instead of
filter()`: This method returns a boolean indicating whether all elements in the array pass the test.with custom filtering: Instead of using
filter()and then
map(), you could use
forEach()` and apply custom filtering logic within the callback function.underscore.js
or ramda
.