var data = [Array(10000)].map((_, i) => i);
Object.fromEntries(data.map(i => [i, i]));
data.reduce((acc, i) => {
acc[i] = i;
return acc;
}, {});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.fromEntries w/Array.map | |
Reduce |
Test name | Executions per second |
---|---|
Object.fromEntries w/Array.map | 9642.3 Ops/sec |
Reduce | 14014.2 Ops/sec |
Let's break down the provided JSON and explain what's being tested.
Benchmark Definition:
The benchmark compares two approaches to create an object from key-value pairs:
Object.fromEntries
with Array.map
Array.reduce
Script Preparation Code:
var data = [...Array(10000)].map((_, i) => i);
This code creates an array of 10,000 elements using the spread operator (...
) and the Array.from()
method. Each element is a function that returns its index (i
) as the value.
Html Preparation Code: None
There's no HTML code provided for this benchmark.
Individual Test Cases:
The benchmark consists of two test cases:
Object.fromEntries(data.map(i => [i, i]));
This line creates an object from key-value pairs using Object.fromEntries()
and maps the array to create the pairs.
data.reduce((acc, i) => {
acc[i] = i;
return acc;
}, {});
This line uses Array.reduce()
to iterate over the array and creates an object with key-value pairs.
Library:
Object.fromEntries()
is a modern JavaScript method introduced in ECMAScript 2015 (ES6). It's a convenient way to create objects from iterable mappings, such as arrays or iterables. The purpose of Object.fromEntries()
is to simplify the process of creating objects from existing data structures.
Special JS Feature/Syntax:
There are no special features or syntax used in this benchmark that would require specific knowledge or expertise.
Pros and Cons:
Here's a brief summary of the pros and cons for each approach:
map()
handles iterationmap()
map()
Other Alternatives:
For creating objects from key-value pairs, other alternatives include:
Array.prototype.reduce()
without Object.fromEntries()
: This approach is more verbose but still effective.forEach()
with set()
: This approach can be faster for large arrays, as it avoids the overhead of map()
.However, these alternatives are not directly comparable to Object.fromEntries()
and Array.map
, as they require more manual iteration and handling of key-value pairs.
Benchmark Result:
The latest benchmark result shows that the Reduce approach performs better than the Object.fromEntries w/Array.map approach. The Safari 15 browser executes the Reduce test case approximately 14,014 times per second, while the Object.fromEntries w/Array.map test case executes it around 9,642 times per second.
Keep in mind that this result may vary depending on the specific hardware and software configurations used to run the benchmark.