<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var arr = [];
for (var i = 0; i < 1000000; i++) {
arr.push(i);
}
var results = _.reduce(arr, (results, result) => {
let key = `a_${result}_b_${result}_c`;
results[key] = results[key] || key;
return results;
});
var results = {};
_.each(arr, (result) => {
let key = `a_${result}_b_${result}_c`;
results[key] = results[key] || key;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce | |
forEach |
Test name | Executions per second |
---|---|
reduce | 1.4 Ops/sec |
forEach | 1.7 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares the performance of two approaches: using _.reduce()
from the Lodash library and using _.forEach()
to achieve the same result. The test creates an array with 1 million elements, populates it with numbers, and then uses each approach to transform the array into an object where each key is a unique identifier composed of three parts.
Options Compared
Two options are compared:
.reduce()
: This method applies a function to each element in the array, accumulating a result. In this case, it's used to create an object where each key is a unique identifier..forEach()
: This method calls a provided callback function once for each element in the array.Pros and Cons of Each Approach
_.reduce()
:_.forEach()
:Lodash Library
The _.reduce()
method is part of the Lodash library, which provides a collection of functional programming helpers. The _.forEach()
method is also provided by Lodash, but it's not necessary for this specific benchmark since we're only using it as a comparison to _.reduce()
.
Special JS Feature or Syntax
There are no special JavaScript features or syntaxes used in this benchmark beyond what's standard for functional programming with Lodash. The focus is on comparing the performance of two different approaches to achieve the same result.
Other Alternatives
If you wanted to write a similar benchmark, you could consider using other libraries or implementing the solution from scratch. Some alternatives include:
Array.prototype.reduce()
instead of Lodash's _.reduce()
forEach
and manually creates the objectKeep in mind that benchmarking can be complex, and the choice of approach will depend on your specific use case and requirements.