<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').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')
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 | 2.2 Ops/sec |
Native (with &&) | 3.1 Ops/sec |
Native (without &&) | 1.7 Ops/sec |
Flow | 2.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Overview
The provided benchmark compares the performance of three different approaches to filter and map data in Lodash:
_.chain()
method to create a chain of functions that manipulate the data.&&
) to combine conditions for filtering data.Library and Purpose
The library used in this benchmark is Lodash, a popular JavaScript utility library that provides a wide range of functions for manipulating data, working with strings, and more.
In the benchmark code, _.noConflict()
is used to prevent conflicts between the original Lodash library and its fp (functional programming) version. This is done by creating a new instance of Lodash (fp
) instead of using the existing one.
Special JS Features or Syntax
There are no special JavaScript features or syntax mentioned in this benchmark, except for the use of _.chain()
to create a chain of functions, which is a common pattern in functional programming. The logical AND operator (&&
) is used to combine conditions, but it's not a special feature.
Pros and Cons of Different Approaches
Other Considerations
_.noConflict()
to prevent conflicts between Lodash versions is not necessary in this benchmark.Alternatives
If you're looking for alternatives to Lodash or want to explore other approaches to filtering and mapping data, here are some options:
for...of
loop or Array.prototype.forEach()
method to iterate over arrays and objects, which can be a more lightweight alternative to using a library like Lodash.Keep in mind that each approach has its own strengths and weaknesses, and the choice of library or technique depends on your specific use case and performance requirements.