<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;
return x;
const x = _.sumBy(window.array, i => i === 3 ? 1 : 0);
return x;
let x = 0;
for (let i = 0; i < window.array.length; i = i + 1) {
if (window.array[i] === 3) {
x = x + 1;
}
}
return x;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Filter length | |
Sum | |
Manual |
Test name | Executions per second |
---|---|
Filter length | 1306135.4 Ops/sec |
Sum | 2000717.6 Ops/sec |
Manual | 49539.4 Ops/sec |
Let's break down what is being tested on the provided JSON.
Benchmark Definition
The benchmark is comparing three different approaches to find the length of an array in JavaScript:
filter()
method: This approach uses the Lodash library to filter the array and then returns the length of the resulting filtered array.sumBy()
method: Similar to the first approach, but instead of returning the length, it returns the sum of all elements in the array that match a certain condition.Options being compared
The three approaches are being compared to determine which one is the most efficient.
Pros and Cons of each approach:
filter()
method:sumBy()
method:filter()
, but can calculate a sum instead of length; also uses Lodash library for optimization.filter()
: relies on external library, may have additional overhead.Library: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for common tasks such as array manipulation, object merging, and more. The filter()
and sumBy()
methods are part of the Lodash library's array functions.
Special JS feature or syntax: None mentioned
There are no special JavaScript features or syntax used in this benchmark.
Other alternatives
If not using Lodash, alternative implementations for the filter()
and sumBy()
methods could be:
Array.prototype.filter()
and Array.prototype.reduce()
However, these alternatives may not provide the same level of optimization or conciseness as Lodash's implementation.
Benchmark preparation code
The script preparation code includes an array window.array
that is used in all three test cases. The Html Preparation Code includes a script tag that loads the Lodash library.
Latest benchmark result
The latest benchmark results show that:
Filter length
and Sum
tests, with execution rates of around 2000-1300 executions per second.These results suggest that Lodash's implementation provides a significant performance boost over manual iteration, while also being more concise and readable.