var ppl = []
for(var i=0; i<100000; 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.length;i++) {
byId[ppl[i].id] = ppl[i]
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
reduce | |
for |
Test name | Executions per second |
---|---|
reduce | 0.1 Ops/sec |
for | 35.6 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares two approaches to create an object from an array of objects: using the reduce()
method versus using a traditional for
loop.
Test Cases
There are two test cases:
**: This test case uses the
reduce()` method to create an object where each key is a unique ID and the corresponding value is the original object.var byId = ppl.reduce((stored, current) => ({ ...stored, [current.id]: current }), {});
This approach is often considered more concise and expressive than the traditional for
loop method.
**: This test case uses a traditional
for` loop to create an object where each key is a unique ID and the corresponding value is the original object.var byId = {};
for (var i = 0; i < ppl.length; i++) {
byId[ppl[i].id] = ppl[i];
}
This approach can be more verbose, but it's often considered easier to understand for developers who are familiar with traditional loop constructs.
Comparison
The benchmark measures the performance of both approaches on a large array of objects (100,000 elements).
Pros and Cons
reduce()
method:
Pros:
Cons:
Traditional for
loop:
Pros:
Cons:
Other Considerations
reduce()
method is often used in conjunction with other methods, such as Object.keys()
or Array.prototype.map()
, which can impact its performance.for
loop approach may have additional overhead due to the need to manually manage the object's properties.Library and Special JS Features
There are no libraries used in this benchmark. However, some JavaScript engines (e.g., V8) provide optimized implementations of the reduce()
method that can improve performance.
No special JavaScript features or syntax are mentioned in this benchmark.
Alternatives
Other approaches to create an object from an array of objects include:
Object.assign()
and Array.prototype.map()
_.mapKeys()
)