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)=>{
var value=mapping(x);
if(filtering(value)) return [acc, value];
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 | 33054.2 Ops/sec |
reduce | 5560.8 Ops/sec |
Let's break down the provided benchmark and its options.
Benchmark Definition
The benchmark is called "filter-map vs reduce 2" and represents a modified version of the classic "map-filter vs reduce" benchmark. The script preparation code defines an array a
with 1000 elements, each containing a number divided by 1000. Three functions are defined:
filtering(x)
: takes a value x
and returns whether it satisfies the condition (x * 114514) % 1 > 0.5
.mapping(x)
: takes a value x
and returns x + 0.1919
.reducing(acc, x)
: takes an accumulator acc
and a value x
, applies the mapping
function to x
, checks if it satisfies the condition using filtering
, and if so, appends the mapped value to the accumulator.Options Compared
The benchmark compares two approaches:
a.filter(filtering).map(mapping)
: This approach first filters the array a
using the filtering
function, then maps each element to a new value using the mapping
function.a.reduce(reducing, [])
: This approach reduces the array a
using the reducing
function as the reduction callback.Pros and Cons of Each Approach
1. a.filter(filtering).map(mapping)
2. a.reduce(reducing, [])
Library Used
The benchmark uses the Array.prototype.filter()
and Array.prototype.map()
methods, which are built-in JavaScript methods. There is no external library used in this benchmark.
Special JS Feature or Syntax
There are no special JavaScript features or syntaxes used in this benchmark. It only relies on standard JavaScript constructs such as functions, loops, and array methods.
Other Alternatives
If you were to rewrite this benchmark with alternative approaches, here are some options:
lodash
that provides its own filtering and mapping functions (e.g., _.filter()
and _.map()
) for potentially improved performance.reduceRight()
or a custom implementation of the reducer function.Keep in mind that these alternatives may not necessarily produce better results and should be evaluated based on their own trade-offs.