<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
function getItems(count) {
let id = 1;
return _.times(count, () => ({
name: "city" + id++,
visited: true
}))
}
var items = getItems(1000)
const result = {};
for(let item of items) {
result[item.name] = item.visited;
}
let initial = {};
const result = items.reduce((accumulator, item) => ({
accumulator,
[item.name]: item.visited
}), initial);
let initial = {};
const result = items.reduce((accumulator, item) => {
accumulator[item.name] = item.visited;
return accumulator;
}, initial);
let result = Object.fromEntries(
items.map(({ name, visited }) => [name, visited])
);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for...of | |
reduce spread | |
reduce mutate | |
object.fromEntries ...map |
Test name | Executions per second |
---|---|
for...of | 4841.6 Ops/sec |
reduce spread | 22.7 Ops/sec |
reduce mutate | 5061.4 Ops/sec |
object.fromEntries ...map | 2513.5 Ops/sec |
Let's break down the provided JSON benchmark and explain what is being tested.
Benchmark Definition
The benchmark is testing four different ways to reduce an array of objects in JavaScript:
for...of
loop and accumulating the results in an object.reduce()
method with the spread operator ({ ...accumulator }
) to accumulate the results in an object.reduce()
method without the spread operator, modifying the accumulator object directly as it iterates over the array.Object.fromEntries()
, mapping each pair to a single value, and then reducing the resulting array.Library and Special Features
https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js
) for its _times()
function, which is used to generate an array of objects.Options Compared
The benchmark compares the performance of four different approaches:
for...of
loop and accumulating the results in an object.reduce()
method with the spread operator ({ ...accumulator }
) to accumulate the results in an object.reduce()
method without the spread operator, modifying the accumulator object directly as it iterates over the array.Object.fromEntries()
, mapping each pair to a single value, and then reducing the resulting array.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Object.fromEntries()
and array methods.Other Considerations
When choosing a method for reducing an array of objects in JavaScript, consider the trade-offs between performance, readability, and maintainability. The benchmark result suggests that Reduce spread is the fastest approach, followed closely by Reduce mutate. However, For...of loop may still be suitable for certain use cases where simplicity and ease of understanding are more important than raw performance.
Keep in mind that this benchmark only tests these four approaches and does not account for other factors like caching, memoization, or optimizations specific to the Lodash library.