<script src="https://raw.githubusercontent.com/lodash/lodash/4.17.15-npm/core.js"></script>
var fruits= {
'apple': { 'name': 'apple', 'number': 5},
'orange': { 'name': 'orange', 'number': 10 }
};
Object.entries(fruits)
.reduce((a, [key, { number }]) => {
a[key] = number;
return a;
}, {}
);
var fruits= {
'apple': { 'name': 'apple', 'number': 5},
'orange': { 'name': 'orange', 'number': 10 }
};
Object.fromEntries(
Object.entries(fruits).map(([key, { number }]) => [key, number])
);
var fruits= {
'apple': { 'name': 'apple', 'number': 5},
'orange': { 'name': 'orange', 'number': 10 }
};
_.mapValues(fruits, 'number');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
native approach with reduce | |
native approach fromEntries | |
lodash mapValues |
Test name | Executions per second |
---|---|
native approach with reduce | 5131705.5 Ops/sec |
native approach fromEntries | 3382933.2 Ops/sec |
lodash mapValues | 6519903.5 Ops/sec |
Let's dive into the benchmark.
Overview
The provided JSON represents a JavaScript microbenchmark test case for measuring the performance of different approaches to map values in an object. The test consists of three individual benchmark definitions, each comparing two methods: a native approach using reduce
, another native approach using fromEntries
with map
, and a third approach using the Lodash library's mapValues
.
Native Approaches
native approach with reduce
: This method uses reduce
to iterate over the object entries, mapping each key-value pair to the value (in this case, the "number" property).reduce
function. Additionally, it may require more memory allocations than necessary.native approach fromEntries
: This method uses the fromEntries
method to create a new array of key-value pairs and then maps each pair to an object with only the "number" property.reduce
approach, especially for large datasets, as it avoids the overhead of function calls. However, it creates an additional array of objects, which may require more memory allocations.fromEntries
method itself is a relatively expensive operation.Lodash Approach
lodash mapValues
: This method uses the Lodash library's mapValues
function to create a new object with values mapped from the original object.Other Considerations
Object.entries
and Object.fromEntries
methods is specific to JavaScript versions 26 and above.Alternatives
In addition to these three approaches, other possible methods for mapping values in an object include:
forEach
loop with a callback functionfor...of
loops and arrow functionsObject.assign()
method (although this might be less efficient than the native approaches)However, these alternatives are not explicitly tested on MeasureThat.net.