var array = Array.from(Array(10000).keys())
Object.fromEntries(array.map(value => [value, value]));
const data = {};
array.forEach(value => data[value] = value);
array.reduce((obj, item) => { obj[item] = item; return obj; }, {});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.fromEntries | |
creating temporary objects | |
Array.reduce |
Test name | Executions per second |
---|---|
Object.fromEntries | 3818.7 Ops/sec |
creating temporary objects | 11886.4 Ops/sec |
Array.reduce | 12038.4 Ops/sec |
Overview
The provided JSON represents a JavaScript microbenchmark test case on the MeasureThat.net website. The benchmark compares three approaches for creating an object from an array: Object.fromEntries
, creating a temporary object, and using Array.reduce
. We'll break down each approach, discuss their pros and cons, and explore other alternatives.
Approaches
Object.fromEntries()
is a method introduced in ECMAScript 2017 (ES7) that creates an object from key-value pairs. In this benchmark, Object.fromEntries(array.map(value => [value, value]))
is used to create an object where each key-value pair is derived from the array.
Pros:
Cons:
This approach involves creating a temporary object using the syntax const data = {};
. The loop then iterates over the array, assigning each value to the object using dot notation (e.g., data[value] = value
).
Pros:
Cons:
Object.fromEntries
The third approach uses Array.reduce()
to create the object. In this case, array.reduce((obj, item) => { obj[item] = item; return obj; }, {})
is used.
Pros:
Cons:
Object.fromEntries
Library and special JS features
In the benchmark, no libraries are explicitly mentioned. However, Array.from()
is used to create an array from a range of numbers (1-10,000), which is not a standard JavaScript feature.
Other considerations
When choosing between these approaches, consider the following factors:
Object.fromEntries
)Alternatives
If you're looking for alternative methods to create objects from arrays in JavaScript, here are a few options:
Array.prototype.reduce()
: Similar to the third approach, but without the Object
context.Array.prototype.forEach()
: While not suitable for creating objects directly, this method can be used with a callback function that creates an object.array[index] = value;
)Keep in mind that these alternatives may have different performance characteristics and code readability compared to the approaches mentioned above.
In conclusion, the choice of approach depends on your specific requirements, code readability preferences, and performance considerations. MeasureThat.net's benchmark can help you understand the relative performance of each approach.