var data = [Array(10000)].map((_, i) => [i, i]);
Object.fromEntries(data);
data.reduce((acc, [k, v]) => {
acc[k] = v;
return acc;
}, {});
data.reduce((acc, [k, v]) => ({ acc, [k]: v }), {});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.fromEntries | |
Reduce (mutate) | |
Reduce (spread) |
Test name | Executions per second |
---|---|
Object.fromEntries | 2453.3 Ops/sec |
Reduce (mutate) | 888.3 Ops/sec |
Reduce (spread) | 91.6 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark is comparing three approaches to create an object from an array of key-value pairs:
Object.fromEntries(data)
data.reduce((acc, [k, v]) => {\r\n acc[k] = v;\r\n return acc;\r\n}, {})
data.reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {})
Options Comparison
The three options are being compared in terms of performance, specifically the number of executions per second.
Object.fromEntries(data)
: This method is a modern addition to JavaScript (introduced in ECMAScript 2015), which creates an object from an array of key-value pairs. It's designed to be fast and efficient.data.reduce((acc, [k, v]) => {\r\n acc[k] = v;\r\n return acc;\r\n}, {})
: This method uses the Array.prototype.reduce() method to iterate over the array and create an object. The callback function takes each key-value pair from the array and adds it to the accumulator object.data.reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {})
: This method is similar to the previous one but uses spread notation ({ ...acc, [k]: v }
) to create a new object for each iteration. The callback function takes each key-value pair from the array and adds it to the accumulator object.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Object.fromEntries(data)
:data.reduce((acc, [k, v]) => {\r\n acc[k] = v;\r\n return acc;\r\n}, {})
:Object.fromEntries()
due to the need for manual iteration.data.reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {})
:Library and Special JS Features
There are no libraries being used in this benchmark. However, Object.fromEntries()
is a special feature introduced in ECMAScript 2015, making it a modern JavaScript feature that's widely supported across different browsers and environments.
Other Alternatives
If you're looking for alternative approaches to create an object from an array of key-value pairs, some other options include:
mapObject
function) or Moment.js (which includes a fromEntries
function).Keep in mind that these alternatives may have different performance characteristics and might require more manual effort to implement.