<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 data = Array(10000000).fill({ a: 'a', b: 1 });
_.chain(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').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')
_.flow(
_.filter(f => f.a === 'a'),
_.filter(f => f.b === 1),
_.filter(f => f.b + 1 === 2),
_.map(f => f.a),
_.filter(f => f === 'a')
)(data)
_.chain(data).filter(f => f.a === 'a' && f.b === 1 && f.b + 1 === 2).map(f => f.a).filter(f => f === 'a').value()
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Chain | |
Native (with &&) | |
Native | |
Flow | |
Chain (with &&) |
Test name | Executions per second |
---|---|
Chain | 0.9 Ops/sec |
Native (with &&) | 1.8 Ops/sec |
Native | 1.0 Ops/sec |
Flow | 1.0 Ops/sec |
Chain (with &&) | 1.6 Ops/sec |
The benchmark defined by the provided JSON tests the performance of various approaches to filter and map through a large dataset (10 million objects) using different methods: Lodash chaining, native JavaScript methods, and a functional composition method provided by Lodash's flow
function.
Lodash Chain:
_.chain(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').value()
Native with &&
:
data.filter(f => f.a === 'a' && f.b === 1 && f.b + 1 === 2).map(f => f.a).filter(f => f === 'a')
Native:
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')
&&
approach, it leverages native methods which are likely faster due to optimizations.Lodash Flow:
_.flow(
_.filter(f => f.a === 'a'),
_.filter(f => f.b === 1),
_.filter(f => f.b + 1 === 2),
_.map(f => f.a),
_.filter(f => f === 'a')
)(data)
Lodash Chain with &&
:
_.chain(data).filter(f => f.a === 'a' && f.b === 1 && f.b + 1 === 2).map(f => f.a).filter(f => f === 'a').value()
From the results:
&&
was slightly slower at 3.13 executions per second.flow
method performed the slowest out of all tests at 1.68 executions per second.When considering alternatives for data manipulation in JavaScript, the following can be noted:
map
, filter
, etc.) is generally recommended for small datasets or when performance is critical.Overall, the choice between using Lodash versus native JavaScript should consider factors such as code readability, performance requirements, and team familiarity with functional programming.