var data = { Array.from(Array(10000).keys()) };
Object.fromEntries(Object.entries(data).map((key, value) => [key, value]));
Object.entries(data).reduce((acc, [k, v]) => {
acc[k] = v.toString();
return acc;
}, {});
Array.from(new Map(Object.entries(data).map((key, value) => [key, value])))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.fromEntries | |
Reduce (reuse object) | |
Map + Array.from |
Test name | Executions per second |
---|---|
Object.fromEntries | 144.9 Ops/sec |
Reduce (reuse object) | 956.8 Ops/sec |
Map + Array.from | 525.2 Ops/sec |
Overview
The provided JSON represents a JavaScript benchmark test case on MeasureThat.net, which compares the performance of three different approaches to create an object from key-value pairs: Object.fromEntries
, reduce
, and Map + Array.from
.
Approaches Compared
Object.fromEntries
: This method creates an object from an array of key-value pairs. It's a relatively new addition to JavaScript, introduced in ECMAScript 2019 (ES10).reduce
: The reduce
method applies a function to each element in an array and reduces it to a single value. In this case, it's used to create an object from key-value pairs by accumulating the values in an object.Map + Array.from
: This approach uses a Map
data structure to store key-value pairs and then converts it to an array using Array.from
. The array is then passed to Object.fromEntries
.Pros and Cons of Each Approach
Object.fromEntries
:reduce
:Object.fromEntries
, especially with large arrays.Map + Array.from
:Object.fromEntries
.Library and Special JS Features
In this benchmark, no external libraries are used. However, note that Map
is a built-in JavaScript data structure introduced in ECMAScript 1999 (ES3), so it's not specific to modern browsers or environments.
There are no special JavaScript features being tested here, as the approaches are relatively standard and widely supported.
Other Alternatives
In addition to these three approaches, other methods for creating objects from key-value pairs include:
Object.keys()
+ reduce()
: This approach uses Object.keys()
to get an array of keys and then reduces it to an object using the reduce()
method.Array.prototype.reduce()
: Similar to the previous approach, but uses Array.prototype.reduce()
instead.These alternatives may have different performance characteristics compared to the approaches tested in this benchmark.