<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) => {
const groupValue = (item['id'] ?? '').toString();
const results = acc[groupValue] ?? [];
results.push(item);
acc[groupValue] = results;
return acc;
}, {})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash | |
Native |
Test name | Executions per second |
---|---|
Lodash | 905.4 Ops/sec |
Native | 378.8 Ops/sec |
Let's break down the provided benchmark definition and its test cases to understand what is being tested.
Benchmark Definition
The benchmark is designed to compare two approaches for grouping an array of objects based on a specific property: id
. The two approaches are:
_groupBy
function from the Lodash library.reduce
method native to JavaScript.Lodash
Lodash is a popular JavaScript utility library that provides various functions for common tasks, including data manipulation. In this case, the _groupBy
function takes two arguments: the array of objects (data
) and a callback function (({ id }) => id
). The callback function returns the value used for grouping, in this case, just the id
property.
The Lodash implementation is likely to be faster because it's implemented in C++ (by Facebook) and then wrapped in JavaScript. This compilation step can provide significant performance benefits compared to interpreting JavaScript code directly on the client-side or server-side.
Pros of using Lodash:
Cons of using Lodash:
Native
The Native approach uses the reduce
method to group the array of objects. The callback function takes two arguments: the accumulator (acc
) and the current item (item
). It returns a new object with the updated grouping value.
Pros of using Native:
Cons of using Native:
Other Considerations
When choosing between these approaches, consider the trade-off between performance and maintainability. If you prioritize speed and are willing to add a dependency, Lodash might be a better choice. However, if you prefer to avoid additional dependencies and are comfortable with more verbose code, Native could be a viable option.
Library (Lodash)
Lodash is a popular JavaScript utility library developed by Facebook. It provides various functions for common tasks, such as data manipulation, string manipulation, and functional programming techniques. Lodash is widely used in the industry and is often included in project dependencies.
Special JS Feature/Syntax
There are no special JavaScript features or syntaxes being tested in this benchmark. The implementation relies on standard JavaScript methods and libraries (Lodash).