<!--your preparation HTML code goes here-->
let foo = new Map();
for (let i = 0; i < 1_000_000; i++) {
foo.set(i, i % 8);
}
[foo.entries()].map(([i, iMod8]) => [i, iMod8.toString()])
Array.from(foo.entries().map(([i, iMod8]) => [i, iMod8.toString()]))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Spread first then map | |
Map first then Array.from |
Test name | Executions per second |
---|---|
Spread first then map | 23.2 Ops/sec |
Map first then Array.from | 12.5 Ops/sec |
The benchmark defined in the provided JSON compares two approaches for transforming entries from a Map
in JavaScript. Specifically, it evaluates the performance of:
Map
into an array using the spread operator ([...]
) and then applying map()
to convert the entries into strings.Array.from
- mapping the entries of the Map
to strings first and then using Array.from()
to create an array from the mapped iterable.Spread first then map
[...foo.entries()].map(([i, iMod8]) => [i, iMod8.toString()])
Map
into a new array, and then it uses the map()
function to transform each entry from a tuple [i, iMod8]
into a new tuple where iMod8
is converted to a string.Map first then Array.from
Array.from(foo.entries().map(([i, iMod8]) => [i, iMod8.toString()]))
map()
function is applied directly to the entries of the Map
, transforming them into string representations. The Array.from()
function is then used to create a new array from the iterable returned by map()
.Map
is already expanded to an array, map()
operates directly on an array, which can sometimes lead to optimizations by the JavaScript engine.Array.from()
could add an additional step that makes the code slightly less readable to those unfamiliar with Array.from()
.map()
and the spread operator. What is faster might not be consistent across environments or even versions of the same engine.forEach
instead of map
: For cases where side effects are needed and a new array is not the primary goal, you could use forEach()
.for...of
loop to manually iterate over the entries, providing further custom optimization but sacrificing the conciseness and expressiveness of functional programming styles.In summary, this benchmark is assessing the overhead and performance differences between two common strategy patterns for data transformation in JavaScript using Maps. Understanding these differences provides insights into performance trade-offs, ease of maintenance, and optimal coding practices.