<script src="//cdnjs.cloudflare.com/ajax/libs/lodash-fp/0.10.4/lodash-fp.min.js"></script>
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30];
function* map(f, xs) {
for (const x of xs) {
yield f(x);
}
}
function* filter(f, xs) {
for (const x of xs) {
if (f(x)) {
yield(x);
}
}
}
function* filterMap(f, g, xs) {
for (const x of xs) {
if (f(x)) {
yield g(x);
}
}
}
var pure = numbers.filter(num => num % 2 === 0).map(num=> ({
result: num
}));
_.flow(_.map(num => ({
result: num
})), _.filter(num => num % 2 === 0))(numbers);
var pure = [filter(num => num % 2 === 0, map(num => ({ result: num }), numbers))];
var pure = [filterMap(num => num % 2 === 0, num => ({ result: num }), numbers)];
var pure = numbers.map(num=> ({ result: num })).filter(({result}) => result % 2 === 0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
pure js | |
lodash fp | |
generator, filter + map | |
generator, filterMap | |
pure js, reversed |
Test name | Executions per second |
---|---|
pure js | 4734605.0 Ops/sec |
lodash fp | 128519.8 Ops/sec |
generator, filter + map | 135683.7 Ops/sec |
generator, filterMap | 600702.4 Ops/sec |
pure js, reversed | 3111443.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
What is being tested?
The benchmark measures the performance of different ways to filter and map an array of numbers in pure JavaScript, using both generator functions and the Lodash library with its fp
(functional programming) version. The tests compare the execution speed of these approaches:
filter
, map
) without any additional libraries.fp
: leveraging the Lodash library's functional programming utilities to simplify and optimize the code.Options being compared
The benchmark compares four different implementations:
Array.prototype.filter()
and Array.prototype.map()
.map
and filter
) to process the array, then flattens the result using another filter
function.filterMap
function to achieve the same result.fp
library to simplify and optimize the code for functional programming.Pros and Cons of each approach
Here are some general pros and cons of each approach:
Other considerations
When writing benchmarks like this one, it's essential to consider factors such as:
Library and its purpose
In this benchmark, the Lodash library is used for its fp
utility functions, which provide a more functional programming-friendly API for working with arrays. The fp
version of these functions is optimized for performance.
Special JS feature or syntax
There are no special JavaScript features or syntaxes being tested in this benchmark, such as async/await, Promises, or ES6+ classes. However, the use of generator functions (map
, filter
) does demonstrate a more functional programming-oriented approach to array processing.