<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var max2 = 500000;
var data = [];
for (var i = 0; i <= max2; i++) { data.push({ id: i }); }
_.groupBy(data, ({ id }) => id)
// Using reduce to mimic _.groupBy
const grouped = data.reduce((acc, item) => {
// Initialize an array for this id if it doesn't exist
if (!acc[item.id]) acc[item.id] = [];
// Push the item into the array for this id
acc[item.id].push(item);
return acc;
}, {});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
Native |
Test name | Executions per second |
---|---|
Lodash | 68.3 Ops/sec |
Native | 40.3 Ops/sec |
The benchmark defined in the provided JSON compares two different approaches for grouping an array of objects based on a unique identifier (in this case, the id
property). The two approaches being evaluated are:
_.groupBy
function.Array.prototype.reduce
method to achieve similar functionality.Script Preparation:
id
ranging from 0 to 499,999. This substantial dataset is essential for evaluating the performance of the two methods over a considerable number of items.HTML Preparation:
_.groupBy
function in the test cases.Lodash Grouping:
_.groupBy(data, ({ id }) => id)
Explanation: This line invokes Lodash’s groupBy
method, where the input data
is passed, and a function returning the id
of each item is used to determine the grouping criterion. Lodash automatically handles the creation of an object whose keys are the unique id
s and the values are arrays containing all objects that have that id
.
Pros:
Cons:
Array.reduce Method:
const grouped = data.reduce((acc, item) => {
if (!acc[item.id]) acc[item.id] = [];
acc[item.id].push(item);
return acc;
}, {});
Explanation: This implementation manually reduces the data array by accumulating results in an object (acc
). It checks if an entry for each id
exists; if not, it initializes an empty array before pushing the current item into it.
Pros:
reduce
are often faster, as they come with less overhead than external libraries. Developers may opt for this when performance is critical.Cons:
From the latest benchmark results:
reduce
): _.groupBy
): The results indicate that the native reduce
approach outperforms Lodash's groupBy
method in this specific scenario, primarily due to less overhead and direct optimization of native functions.
Alternatives:
Map
for performance gains on larger datasets as it maintains insertion order and provides efficient key-value pair storage.Context:
This benchmark provides crucial insights for software engineers into the trade-offs between using utility libraries versus native JavaScript functions, particularly for performance-sensitive tasks.