var data = Array.from(Array(10000).keys())
data.reduce((acc, v) => ({
acc,
[v]: v.toString()
}), {});
Object.fromEntries(data.map(value => [value, value.toString()]));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Reduce | |
Object |
Test name | Executions per second |
---|---|
Reduce | 72.7 Ops/sec |
Object | 891.3 Ops/sec |
I'll break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares two approaches to creating an object from an array: using Object.fromEntries
(also known as "Object.fromEntries" or simply "fromEntries") on one hand, and reducing the array to create the object on the other hand.
Options Being Compared
Pros and Cons of Each Approach
Library Used
In this benchmark, Object.fromEntries
uses a built-in JavaScript method, which means no external library is required.
Special JS Feature or Syntax
The benchmark uses a feature called "Spread operator" (...
) introduced in ECMAScript 2015 (ES6). This operator allows creating new objects by spreading the properties of an existing object.
In this case, the spread operator is used inside the Object.fromEntries
callback function to create key-value pairs from each element in the array.
Other Considerations
The benchmark measures performance on a specific input size (10,000 elements) and uses a Chrome 103 browser version. The results are likely influenced by various factors such as:
Alternative Approaches
Other possible approaches to create an object from an array include:
Array.prototype.reduce.call(null, {}, ...)
: This method is similar to the reduce approach mentioned earlier but uses the call
method to pass the initial object as the accumulator.var obj = {}; for (var i = 0; i < data.length; i++) { obj[data[i]] = data[i].toString(); }
Array.prototype.forEach
: data.forEach((value, index) => ({ [index]: value.toString() }))
These alternatives may have different performance characteristics compared to the two main approaches being benchmarked (Object.fromEntries and reduce).