<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
var fp = _.noConflict();
var data = Array(10000000).fill({ a: 'a', b: 1 });
_.chain(data).filter(f => f.a === 'a' && f.b === 1 && f.b + 1 === 2).map(f => f.a).filter(f => f === 'a').value()
data.filter(f => f.a === 'a' && f.b === 1 && f.b + 1 === 2).map(f => f.a).filter(f => f === 'a')
data.filter(f => f.a === 'a').filter(f => f.b === 1).filter(f => f.b + 1 === 2).map(f => f.a).filter(f => f === 'a')
fp.flow(
fp.filter(f => f.a === 'a'),
fp.filter(f => f.b === 1),
fp.filter(f => f.b + 1 === 2),
fp.map(f => f.a),
fp.filter(f => f === 'a')
)(data)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Chain | |
Native (with &&) | |
Native (without &&) | |
Flow |
Test name | Executions per second |
---|---|
Chain | 0.5 Ops/sec |
Native (with &&) | 0.4 Ops/sec |
Native (without &&) | 0.2 Ops/sec |
Flow | 0.3 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks and explore what's being tested in this benchmark.
Benchmark Overview
The provided benchmark compares four approaches to filter and transform an array:
Options Compared
Each test case uses a different approach to achieve the same result, which is to filter and map an array of objects.
_.chain()
method from Lodash to create a pipelined function chain that performs the filtering and mapping operations. The &&
operator is used to short-circuit the evaluation of the expressions.filter()
and map()
methods, taking advantage of the implicit short-circuiting behavior of the &&
operator in conditional statements.filter()
and map()
methods as above but without the &&
operator.filter()
, map()
, and filter()
functions to achieve the same result. The &&
operator is used in a different context, as part of a conditional expression.Pros and Cons
Here are some observations about each approach:
&&
also reduces computation overhead.&&
operator in conditional statements.filter()
and map()
.with &&
approach.Other Considerations
The benchmark also highlights the importance of:
Alternatives
Other approaches to achieve similar results might include:
lodash-es
or ramda
for functional programming and filtering/mapping operations.Array.prototype.filter()
and Array.prototype.map()
with more advanced techniques, such as using forEach()
or reduce()
.filter()
and map()
methods.Keep in mind that these alternatives might have their own trade-offs regarding performance, code readability, maintainability, and compatibility.