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;
return acc;
}, {});
Object.entries(data).reduce((acc, [k, v]) => ({
acc,
[k]: v
}), {});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.fromEntries | |
Reduce (reuse object) | |
Reduce (creating temporary objects) |
Test name | Executions per second |
---|---|
Object.fromEntries | 281.1 Ops/sec |
Reduce (reuse object) | 3337.6 Ops/sec |
Reduce (creating temporary objects) | 103.2 Ops/sec |
Let's break down the provided benchmark JSON and explain what is tested, compared, and considered in this JavaScript microbenchmark.
Benchmark Overview
The benchmark compares three approaches to create an object from an array of key-value pairs:
Object.fromEntries
Object.entries.reduce
(with a reusable object as the accumulator)Object.entries.reduce
(creating temporary objects for each iteration)Options Compared
Object.fromEntries
: A modern JavaScript method introduced in ECMAScript 2015, which creates an object from an array of key-value pairs.Object.entries.reduce
with a reusable object: This approach uses the reduce()
method to accumulate values into an object, reusing the existing object as the accumulator.Object.entries.reduce
creating temporary objects: In this version, a new object is created for each iteration, accumulating values.Pros and Cons
reduce()
method and potential object cloning.Library/Utility Used
None are explicitly mentioned in the benchmark code, but Array.from()
is used to create an array from a specified number of keys. This method is a built-in utility function in JavaScript.
Special JS Feature/Syntax
None are explicitly mentioned or used in this benchmark.
Other Alternatives
Additional approaches to create an object from an array of key-value pairs might include:
Array.prototype.reduce()
: Similar to the second approach, but uses reduce()
on the Array
prototype instead.for...of
loop and Object.defineProperty()
or similar methods.It's worth noting that the choice of approach often depends on the specific use case, performance requirements, and personal preference.