<!--your preparation HTML code goes here-->
const make = (length) => ({
id: length,
items: Array.from({ length }, () => make(length / 2))
})
const data = make(20)
const ids = Array.from(new Set(
data.items.map(
i => i.items.map(
ii => ii.items
)
).flat(2)
.filter(item => item.id % 2 === 0)
.map(item => item.id.toString())
))
const items = new Set()
for (const i of data.items)
for (const ii of i.items)
for (const item of ii.items)
if (item.id % 2 === 0) items.add(item.id.toString())
const ids = Array.from(items)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Map | |
Loop |
Test name | Executions per second |
---|---|
Map | 55144.3 Ops/sec |
Loop | 143741.3 Ops/sec |
The benchmark titled "Populating a Set" involves testing two different JavaScript approaches to collect unique item IDs from a nested data structure. The data is generated through a recursive function that creates an object of "length" containing nested items, thereby simulating a complex dataset.
Test Case: Map
const ids = Array.from(new Set(
data.items.map(
i => i.items.map(
ii => ii.items
)
).flat(2)
.filter(item => item.id % 2 === 0)
.map(item => item.id.toString())
));
map
, flat
, filter
, and Set
methods.map
: Transforms the nested structure of items into a flat array.flat(2)
: Flattens the resulting array by two levels, bringing all IDs into a single array.filter
: Selects only those items whose id
is even.Set
: Ensures uniqueness of the IDs extracted.Array.from
: Converts the Set back into an array.map
and flat
, leading to increased memory allocation and function call overhead.Test Case: Loop
const items = new Set();
for (const i of data.items)
for (const ii of i.items)
for (const item of ii.items)
if (item.id % 2 === 0) items.add(item.id.toString());
const ids = Array.from(items);
for...of
loops to iterate through the nested structure.Set
is used to store unique IDs directly during iteration.The benchmark results indicate the following:
This indicates a significant performance advantage for the Loop approach in this scenario.
reduce
for accumulation or libraries like Lodash might be explored for more advanced data manipulation scenarios. Lodash provides variations of the map
, filter
, and uniq
functionalities with potential performance optimizations.In summary, the benchmark evaluates two different JavaScript methods of extracting unique, even IDs from a complex dataset, providing insights into performance trade-offs between a functional programming style and traditional iterative approaches.