<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>
var object = {
'a': {
'key': 'a',
'foo': 123123,
'bar': 123,
'fobar': 456
}
};
var array = [
{
'key': 'b',
'foo': 67563,
'bar': 6345,
'fobar': 3425
},
{
'key': 'c',
'foo': 34532,
'bar': 123412,
'fobar': 534532
},
{
'key': 'd',
'foo': 1234321,
'bar': 435234,
'fobar': 346457
},
{
'key': 'e',
'foo': 23523,
'bar': 124325,
'fobar': 2134235
},
{
'key': 'f',
'foo': 1235213,
'bar': 346346,
'fobar': 213423
}
];
array.reduce(function(acc, cur) {
acc[cur.key] = cur;
return acc;
}, Object.assign({}, object));
_.reduce(array, function(acc, cur) {
acc[cur.key] = cur;
return acc;
}, Object.assign({}, object));
Object.assign({}, object, _.keyBy(array, 'key'));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.reduce() | |
_.reduce() | |
_.keyBy() |
Test name | Executions per second |
---|---|
Array.prototype.reduce() | 1131684.4 Ops/sec |
_.reduce() | 900060.5 Ops/sec |
_.keyBy() | 474935.3 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, compared options, pros and cons, and other considerations.
Benchmark Overview
The test case is designed to measure the performance of three different methods for converting an array into an object by key:
Array.prototype.reduce()
_
(Lodash) function .reduce()
_
(Lodash) function .keyBy()
with Object.assign()
as the accumulator.Options Compared
The three options are being compared in terms of execution time, which is represented by the "ExecutionsPerSecond" value.
Array.prototype.reduce()
: This method uses a simple loop to iterate through the array and assign each object to an empty object._
(Lodash) function .reduce()
: This method uses Lodash's reduce()
function, which is optimized for performance. It takes advantage of the iterator protocol and lazy evaluation to reduce memory allocation._
(Lodash) function .keyBy()
: This method uses Lodash's keyBy()
function, which creates a new object with the original array elements as values. The resulting object has the same structure as the original array.Pros and Cons
Here are some pros and cons of each approach:
Array.prototype.reduce()
:_
(Lodash) function .reduce()
:Array.prototype.reduce()
due to Lodash's optimized implementation._
(Lodash) function .keyBy()
:.reduce()
.Other Considerations
Array.prototype.reduce()
has the highest memory usage due to the need to create new objects for each iteration, while _
(Lodash) function .keyBy()
has a lower memory overhead..reduce() > .keyBy() > reduce()
, with Lodash's optimized implementation providing the best performance.Alternatives
If you're looking for alternatives to these options, here are some alternatives:
Object.fromEntries()
(ES6+) instead of Array.prototype.reduce()
or _
(Lodash) function .reduce()
. This method is more concise and has a lower memory overhead.Keep in mind that the choice of implementation depends on your specific use case and performance requirements.