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.toString();
return acc;
}, {});
Object.entries(data).reduce((acc, [k, v]) => ({
acc,
[k]: v.toString()
}), {});
const res = {};
for (const [k, v] of Object.entries(data)) {
res[k] = v.toString();
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.fromEntries | |
Reduce (reuse object) | |
Reduce (creating temporary objects) | |
for |
Test name | Executions per second |
---|---|
Object.fromEntries | 293.9 Ops/sec |
Reduce (reuse object) | 3186.1 Ops/sec |
Reduce (creating temporary objects) | 104.6 Ops/sec |
for | 3276.7 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark is comparing the performance of three different approaches to create an object from an array of key-value pairs:
Object.fromEntries
reduce
(with reusing the same object)for
loopEach approach has its own pros and cons, which we'll discuss below.
Options Compared
Object.fromEntries
: a modern JavaScript method introduced in ECMAScript 2015 that creates an object from an array of key-value pairs.reduce
: a method on the Array prototype that applies a function to each element in the array, reducing it to a single output value. In this case, it's used to create an object by reusing the same accumulator object.for
loop: a traditional looping construct that iterates over the array and creates an object manually.Pros and Cons of Each Approach
Object.fromEntries
:reduce
(with reusing the same object):for
loop:Library Used
In this benchmark, no external library is used. The only custom function being compared is Object.fromEntries
.
Special JavaScript Features or Syntax
None are explicitly mentioned in the provided code snippets.
Other Considerations
Object.fromEntries
might be more efficient due to its optimized implementation.Object.fromEntries
is only supported in modern browsers. This could affect the benchmark's results across different environments.Alternatives
If you need to support older browsers or want even more flexibility with your array processing, you could consider using other methods like:
Array.prototype.forEach
and creating an object manually.reduce
method specifically optimized for performance.Keep in mind that these alternatives might change the benchmark's results or complexity, so it's essential to carefully evaluate their trade-offs.