var data = [];
for (var i=0;i<10000;i++) {
data.push({key: 'key' + i, value : 'value' + i})
}
Object.fromEntries(data.map(({key, value}) => [key, value]))
data.reduce((acc, current) => {
acc[current.key] = current.value;
return acc;
}, {});
let out = {};
for(let i=0 ; i<data.length ; i++) {
out[data[i].key] = data[i].value;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
fomEntries | |
reduce | |
for |
Test name | Executions per second |
---|---|
fomEntries | 611.5 Ops/sec |
reduce | 1710.0 Ops/sec |
for | 431.3 Ops/sec |
Let's dive into the benchmark analysis.
Benchmark Definition JSON
The provided JSON defines three microbenchmarks:
Object.fromEntries(data.map(({key, value}) => [key, value]))
data.reduce((acc, current) => {\r\n acc[current.key] = current.value;\r\n return acc;\r\n }, {})
let out = {};\r\nfor(let i=0 ; i<data.length ; i++) {\r\n out[data[i].key] = data[i].value;}
These benchmarks test different approaches to iterate over and populate an object.
Options Compared
The three benchmarks compare the performance of:
Pros and Cons
Library and Purpose
The Object.fromEntries
method uses the native JavaScript API, which is not explicitly a library but an built-in feature since ECMAScript 2017. The reduce
method also relies on the native JavaScript API, while the for loop uses the built-in array iteration features.
Special JS Feature or Syntax
There are no special JavaScript features or syntax used in this benchmark except for the use of template literals (\r\n
) in the script preparation code and some minor differences in formatting between benchmarks (e.g., using semicolons instead of line breaks).
Alternatives
Other alternatives to these benchmarks might include:
Array.prototype.forEach
with a callback functionKeep in mind that the choice of approach depends on the specific use case, dataset size, and desired level of performance.
I hope this explanation helps!