var ppl = []
for(var i=0; i<20000; 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 | 4.0 Ops/sec |
for | 112.7 Ops/sec |
Let's break down the provided JSON data to understand what is being tested.
Benchmark Definition: The benchmark measures the performance of two approaches to create an object from an array:
reduce
method to iterate over the array and create an object where each element in the array becomes a key-value pair.for
loop to iterate over the array and create an object where each element in the array becomes a key-value pair.Options Compared:
reduce
method is a built-in JavaScript function that applies a specified function against an accumulator and each element of the array (from left to right) to reduce it to a single value.for
loop uses an explicit counter variable to iterate over the elements of the array.Pros and Cons:
reduce
reduce
methodLibrary Usage: None of the provided benchmark definitions use any external libraries.
Special JavaScript Features/Syntax: The provided benchmarks do not utilize any special JavaScript features or syntax, such as async/await, generators, or decorators. The focus is on comparing two common approaches to create an object from an array.
Other Alternatives:
Object.fromEntries
(a modern method introduced in ECMAScript 2019): var byId = Object.fromEntries(ppl.map((ppl) => [ppl.id, ppl]));
Keep in mind that the choice of approach often depends on the specific requirements and constraints of your project. The provided benchmarks aim to provide a neutral comparison between two common approaches, allowing developers to make informed decisions about their coding choices.