var ppl = []
for(var i=0; i<10000; i++) {
ppl.push({ id: i, name: i+"" })
}
var byId = ppl.reduce((stored, current) => ({ stored, [current.id]: current }), {});
var byId = {}
for(var i=0;i<ppl.lenght;i++) {
byId[ppl[i].id] = ppl[i]
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce | |
forcycle |
Test name | Executions per second |
---|---|
reduce | 36.0 Ops/sec |
forcycle | 10207771.0 Ops/sec |
Let's break down what's being tested in the provided JSON.
Benchmark Definition
The benchmark measures the performance difference between two approaches for converting an array of objects into an object with the same structure, but using different methods: reduce()
and a traditional for
loop.
Options Compared
Array.prototype.reduce()
method to iterate over the array of objects and create a new object with the required structure.for
loop to iterate over the array of objects and create a new object with the required structure.Pros and Cons
Library Used
None of the methods use a specific library, but reduce()
is a built-in method provided by the JavaScript language itself. However, if we consider the purpose of the library-like approach in the for
loop (i.e., creating an object with dynamic keys), one might argue that it's similar to using a library like Lodash or Ramda for working with objects.
Special JS Feature/Syntax
The benchmark uses const
and var
declarations, which are part of the ECMAScript 5 specification. The use of template literals (e.g., ${i+\"\"}
) is also present in both code snippets.
Other Alternatives
If you're interested in exploring other approaches for converting arrays to objects, here are a few alternatives:
{ ... }
) with object destructuring to create a new object with dynamic keys.Array.prototype.map()
or other array methods.forEach
method to iterate over the array of objects and create a new object with dynamic keys.Here's an example of how the spread operator could be used:
var byId = {};
ppl.forEach((person) => {
byId[person.id] = person;
});
And here's an example using Object.fromEntries()
:
var byId = Object.fromEntries(ppl.map((person) => [person.id, person]));