const data = Array.from(Array(1000).keys());
var map = new Map(data.map((o) => [o, o]));
var array = [data];
const filtered = [];
for (const o of map.values()) {
if (o%2 === 0) filtered.push(o);
}
const filtered = [];
map.forEach(o => {
if (o%2 === 0) filtered.push(o)
});
const filtered = array.filter(o => o % 2 === 0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
iterate on map with values() and filter | |
iterate on map with forEach() and filter | |
iterate on array and filter |
Test name | Executions per second |
---|---|
iterate on map with values() and filter | 155168.3 Ops/sec |
iterate on map with forEach() and filter | 55770.3 Ops/sec |
iterate on array and filter | 193974.1 Ops/sec |
Benchmark Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The benchmark in question involves measuring the performance of three different approaches for filtering an array or map.
Benchmark Definition JSON
The benchmark definition JSON provides the following information:
Array.from
and Map
.Test Cases
The test cases are defined as an array of objects, each representing a single test. The test case definition includes:
There are three test cases:
values()
method of the Map object to iterate over its entries, and filters out odd numbers using an array method (push
).forEach()
method of the Map object to iterate over its entries, and filters out odd numbers using an array method (push
).filter()
method of the Array object to filter out odd numbers.Comparison
The three test cases compare different approaches for filtering arrays or maps:
values()
, then filtering with an array method (push
).forEach()
, then filtering with an array method (push
).filter()
method of the Array object.Pros and Cons
Here's a brief analysis of each approach:
values()
and an additional array method.In terms of performance, the filter()
method is generally the fastest option. The forEach()
method with filtering can be slower due to the overhead of iterating over each element using a callback function. Iterating over a Map object using values()
and an additional array method can be slower as well, but the difference is likely minimal.
Alternative Approaches
Other approaches to filter arrays or maps include:
map()
with a callback function (e.g., map(o => o % 2 === 0)
).reduce()
with an accumulator and callback function._.filter()
) or Ramda (R.filter()
).Keep in mind that each approach has its own trade-offs between conciseness, readability, and performance.
Special JavaScript Features or Syntax
This benchmark does not use any special JavaScript features or syntax beyond the standard language.