<script src="https://cdn.jsdelivr.net/lodash/4.16.2/lodash.min.js"></script>
window.array = [1, 4, 3, 4, 2, 2, 1, 5, 3, 5, 1, 4, 3, 4, 2, 2, 1, 5, 3, 5, 1, 4, 3, 4, 2, 2, 1, 5, 3, 5, 1, 4, 3, 4, 2, 2, 1, 5, 3, 5, 1, 4, 3, 4, 2, 2, 1, 5, 3, 5];
const x = _.filter(window.array, i => i === 3).length
const x = _.sumBy(window.array, i => i === 3 ? 1 : 0)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Filter length | |
Sum |
Test name | Executions per second |
---|---|
Filter length | 777025.0 Ops/sec |
Sum | 834411.1 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Definition
The benchmark is testing two different approaches to filter an array in JavaScript: using _.filter()
with a callback function to get the length of the filtered array, and using _.sumBy()
that sums up values where a condition is met (in this case, i === 3
) and then converts the result to length.
Options Compared
The two options are:
_.filter()
to create a new array with elements that match the condition (i === 3
), and then gets the length of the resulting array using .length
._.sumBy()
that sums up values where a condition is met (i === 3 ? 1 : 0
). The result is then converted to length using the length
property.Pros and Cons of Each Approach
_.sumBy()
's behavior.Library: Lodash
Lodash (pronounced "lodash") is a popular JavaScript utility library that provides a wide range of functions for tasks like array manipulation, string manipulation, and more. In this benchmark, _.filter()
and _.sumBy()
are used from the lodash
library to perform the filtering and summing operations.
Special JS Feature/Syntax
There isn't any special JavaScript feature or syntax being tested in this benchmark. The focus is on comparing two different approaches to achieve a specific goal (filtering an array).
Other Alternatives
If you were to implement these benchmarks yourself, you could also consider using other libraries like:
Array.prototype.filter()
and Math.length
for the _.filter() + Length
approach.Array.prototype.reduce()
with a custom callback function for the _.sumBy() + Condition
approach.However, it's worth noting that Lodash provides these functions with optimized implementations and may be more efficient than implementing them yourself.