<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var max2 = 100000;
var data = [];
for (var i = 0; i <= max2; i++) { data.push({ id: i }); }
_.groupBy(data, ({ id }) => id)
data.reduce((acc, item) => {
acc[item.id] = [ (acc[item.id] || []), item];
return acc;
}, {})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
Native |
Test name | Executions per second |
---|---|
Lodash | 142.3 Ops/sec |
Native | 45.1 Ops/sec |
Let's break down the benchmark and explain what's being tested, compared options, pros and cons, and other considerations.
Benchmark Overview
The benchmark is designed to compare the performance of two approaches for grouping data: Lodash's groupBy
function and JavaScript's native Array.reduce
method. The test case uses a large dataset of 100,000 objects with an "id" property.
Options Compared
The two options being compared are:
groupBy
function: This is a external library that provides a convenient way to group data by a common attribute (in this case, the id
property). The implementation is provided by Lodash and is available for download from a CDN.Array.reduce
method: This is a built-in method in JavaScript that allows you to iterate over an array and apply a reduction function to each element.Pros and Cons
Lodash's groupBy
function:
Pros:
Cons:
JavaScript's native Array.reduce
method:
Pros:
Cons:
groupBy
functionLibrary: Lodash
Lodash is a popular utility library for JavaScript that provides a wide range of functional programming helpers, including the groupBy
function. The library includes many other useful functions for tasks such as array manipulation, string formatting, and object manipulation.
Special JS Feature or Syntax: None mentioned
There are no special JavaScript features or syntax used in this benchmark. The implementation focuses on demonstrating the performance difference between two standard approaches to grouping data.
Alternatives
Other alternatives for grouping data include:
Array.prototype.forEach
with a callback functionArray.prototype.map
and Array.prototype.reduce
It's worth noting that the choice of implementation depends on the specific requirements and constraints of your project. If you need a simple, high-performance solution for grouping data, native Array.reduce
may be a good choice. However, if you prioritize convenience, readability, and maintainability, Lodash's groupBy
function may be a better fit.