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()
}), {});
Object.entries(data).reduce((acc, [k, v]) => {
acc.set(k, v.toString())
return acc;
}, new Map());
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.fromEntries | |
Reduce (reuse object) | |
Reduce (creating temporary objects) | |
Map |
Test name | Executions per second |
---|---|
Object.fromEntries | 240.9 Ops/sec |
Reduce (reuse object) | 2787.5 Ops/sec |
Reduce (creating temporary objects) | 97.0 Ops/sec |
Map | 1229.1 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, compared, and their pros/cons.
Benchmark Definition:
The benchmark compares three methods to create an object from an array of key-value pairs:
Object.fromEntries
Array.prototype.reduce
(with reuse object approach)Array.prototype.reduce
(with creating temporary objects approach)Test Cases:
Each test case represents one of the above methods being tested on a specific dataset. The dataset is created using Array.from(Array(10000).keys())
, which generates an array of 10,000 numbers.
Here's a brief explanation of each test case:
Array.prototype.reduce
to create a new object by accumulating values in an accumulator object. The reuse object approach avoids creating temporary objects by reusing the same accumulator object for all iterations.Array.prototype.reduce
with a Map
object as the accumulator, which avoids creating temporary objects by using the map's built-in methods.Pros and Cons:
Here are some pros and cons of each approach:
Map
data structure, avoids creating temporary objects.Map
API.Library/Technology Used:
The benchmark utilizes:
Special JS Features/ Syntax:
The benchmark uses:
Alternatives:
Other alternatives to compare would include:
Array.prototype.forEach
instead of Array.prototype.reduce
.for...in
loops or string concatenation.Keep in mind that the choice of approach depends on the specific use case and performance requirements.