var array = Array.from({ length: 10001 }, (_, index) => index);
Object.fromEntries(array.map((n) => [`db/path/${n}`, null]));
array.reduce((acc, n) => {
acc[`db/path/${n}`] = null;
return acc;
}, {});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.fromEntries | |
Reduce (reuse object) |
Test name | Executions per second |
---|---|
Object.fromEntries | 442.7 Ops/sec |
Reduce (reuse object) | 755.3 Ops/sec |
The benchmark described in the provided JSON tests two different JavaScript approaches for creating an object from an array of indices ranging from 0 to 10,000. The focus is on performance comparison between two techniques for constructing an object where the keys follow a specific pattern. Here's the breakdown of what is tested, the options compared, and other relevant considerations:
Object.fromEntries with Array.map
Object.fromEntries(array.map((n) => [`db/path/${n}`, null]));
Array.prototype.map()
to transform the array into an array of key-value pairs (in this case, an array of tuples where each tuple has a key formatted as a string and a value of null
). The resulting array is then passed to Object.fromEntries()
, which constructs an object from the key-value pairs.Array.reduce
array.reduce((acc, n) => {
acc[`db/path/${n}`] = null;
return acc;
}, {});
Array.prototype.reduce()
, starting with an empty object ({}
) as the accumulator. For each element in the array, it adds a new property to the accumulator object, with a key formatted similarly as in the first approach, effectively building the object directly.Pros:
Object.fromEntries()
with mapping makes it clear that you are converting key-value pairs directly into an object.Cons:
reduce
, likely due to the overhead of creating an intermediate array of key-value pairs.Pros:
Cons:
reduce
.Object.fromEntries
may be preferable despite its relatively slower performance. However, if performance is a priority and the structure is straightforward, using reduce
may be the better choice.for
loops, which may offer performance benefits in certain contexts, such as when the browser's optimization engines have trouble with functional methods. For very large datasets or performance-critical code, reviewing the specific situation and profiling and optimizing could yield even better results.In summary, this benchmark illustrates the trade-offs between modern declarative constructs and imperative code in JavaScript, showing clear performance differences while also highlighting considerations of code clarity and intent.