<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;
let array = window.array;
let len = array.length;
for (let i = 0; i < len; i++) {
if (array[i] === 3) {
x++;
}
}
return x;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Filter length | |
Sum | |
Manual |
Test name | Executions per second |
---|---|
Filter length | 2962305.8 Ops/sec |
Sum | 3481808.5 Ops/sec |
Manual | 12720138.0 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Overview
The benchmark compares the performance of three approaches to count the number of occurrences of the value 3
in an array: using Lodash's filter()
function with the length property (Filter length
), using Lodash's sumBy()
function with a custom callback (Sum
), and manually iterating through the array (Manual
).
Lodash Library
The benchmark uses Lodash, a popular JavaScript utility library. In this case, it's used for two functions:
_.filter()
: filters an array to return only elements that pass the test implemented by the provided function._.sumBy()
: calculates the sum of each element in the array using the provided function.Options Compared
The benchmark compares the performance of three options:
filter()
function with the length property to count the number of occurrences of 3
.sumBy()
function with a custom callback to count the number of occurrences of 3
(by returning 1 for each occurrence and 0 otherwise).for
loop to count the number of occurrences of 3
.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Device Platform and OS
The benchmark is run on a Windows desktop with Chrome 118 browser. The results are executed per second, indicating the number of times each approach is executed in one second.
Other Considerations
window.array
) to keep the dataset manageable.Manual
approach assumes that the array elements are integers and that 3
will be present multiple times. If this assumption is not valid, the results may not be accurate.Alternatives
If you want to test similar benchmarks without using Lodash, you can explore other JavaScript libraries or built-in functions that provide filtering and summing capabilities. Some alternatives include:
Array.prototype.filter()
(native JavaScript function)Array.prototype.every()
and Array.prototype.some()
(native JavaScript functions)Array.prototype.reduce()
with a custom callback (native JavaScript function)