var arr10k = Array.from(Array(10000)).map((x, i) => ({ x1: i, x2: i * 2, x4: i * 4 }));
arr10k.reduce((acc, x) => acc.set(x.x1, x), new Map());
new Map(arr10k.map(x => [x.x1, x]));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Map from .reduce | |
Map from .map |
Test name | Executions per second |
---|---|
Map from .reduce | 894.5 Ops/sec |
Map from .map | 679.4 Ops/sec |
Overview of the Benchmark
The provided benchmark is designed to compare the performance of two approaches for creating and manipulating maps in JavaScript: using .reduce()
versus using .map()
. The test case consists of an array of 10,000 objects, each with three properties (x1
, x2
, and x4
).
Options Compared
Two options are compared:
.reduce()
method to create a map, where each iteration of the accumulator accumulates values in the map..map()
method to create an array of arrays, and then converts this array into a map using the spread operator (new Map(arr)
).Pros and Cons
map()
and reduce()
.Library Used
None. The benchmark does not use any external libraries or dependencies.
Special JS Features/Syntax (Not Applicable)
There are no special JavaScript features or syntax used in this benchmark.
Other Considerations
.reduce()
, the accumulator accumulates values in memory, which can lead to cache locality issues. In contrast, when using .map()
and then converting to a map, each value is stored separately in memory, reducing cache locality concerns..map()
, the array of arrays is created first, which may increase memory usage compared to using .reduce()
.Alternatives
If you were to recreate this benchmark, here are some alternative approaches:
Promise.all()
instead of .map()
and then converting to a map.Array.from()
with an array of functions, similar to the current .map()
approach.Set
or WeakMap
, which may offer different performance characteristics.Keep in mind that these alternatives may alter the benchmark's focus and results, so it's essential to carefully consider your goals when recreating the benchmark.