var data = Array.from(Array(10000).keys());
var f = v => v + ';';
Object.fromEntries(data.map(x => [x, f(x)]));
data.reduce((acc, x) => ({acc, [x]: f(x)}), {});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
map & fromEntries | |
reduce |
Test name | Executions per second |
---|---|
map & fromEntries | 2947.0 Ops/sec |
reduce | 178.3 Ops/sec |
I'll break down the provided benchmark JSON and explain what's being tested, compared, and their pros and cons.
Benchmark Definition
The benchmark is comparing two approaches:
Object.fromEntries
with an array of key-value pairs created using data.map()
.Array.prototype.reduce()
to accumulate an object with key-value pairs from the same data source.Both approaches aim to create an object from a data set, but they have different implementation details.
Options Compared
The two options are:
Object.fromEntries
: A modern JavaScript method introduced in ECMAScript 2017, which creates an object by passing an array of key-value pairs.Array.prototype.reduce()
: A common method for accumulating data in an array, which can be used to create an object.Pros and Cons
Object.fromEntries
:Array.prototype.reduce()
:Object.fromEntries
, might lead to additional computations.Library/Functionality
There is no specific library used in this benchmark. Both Object.fromEntries
and Array.prototype.reduce()
are built-in JavaScript functions.
Special JS Feature/Syntax
The benchmark uses the modern JavaScript feature ECMAScript 2017
( Introduced in Firefox 91), specifically Object.fromEntries
. This feature was added to provide a concise way to create objects from arrays of key-value pairs.
Other Alternatives
Alternative approaches could include:
Array.prototype.forEach()
or Array.prototype.forEach.call()
to iterate over the data array and create an object.In conclusion, this benchmark compares two approaches to create an object from a data set: using Object.fromEntries
with modern JavaScript feature (ECMAScript 2017) and using Array.prototype.reduce()
. Both options have their pros and cons, and the choice ultimately depends on the specific use case, personal preference, or project requirements.