var objArray = [{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}, {id: 7}, {id: 8}, {id: 9}, {id: 10}, {id: 11}, {id: 12}, {id: 13}, {id: 14}, {id: 15}, {id: 16}, {id: 17}, {id: 18}, {id: 19}, {id: 20}];
var idArray = [1];
var filteredObjArray = objArray.filter(obj => idArray.includes(obj.id));
var filteredObjArray = idArray.flatMap(id => objArray.find(obj => obj.id === id) || []);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
filter | |
flatMap |
Test name | Executions per second |
---|---|
filter | 1464960.1 Ops/sec |
flatMap | 5023242.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Definition
The benchmark is designed to compare the performance of two approaches: filtering an array using Array.prototype.filter()
and flattening an array using Array.prototype.flatMap()
. The test case uses a JavaScript object array objArray
containing 20 objects with an "id" property, as well as an array idArray
containing a single value.
Script Preparation Code
The script preparation code defines the objArray
and idArray
variables, which are used in the benchmark. The var idArray = [1];
line creates an array containing only one element, which is used to filter or map the objects in objArray
.
Html Preparation Code
There is no HTML preparation code provided, so we can assume that this step is not relevant for this particular benchmark.
Individual Test Cases
The test cases are defined as separate benchmarks:
Array.prototype.filter()
method to create a new array containing only the objects in objArray
whose "id" property matches one of the values in idArray
. The condition used is obj => idArray.includes(obj.id)
.Array.prototype.flatMap()
method to create a new array containing the results of applying the function (id => objArray.find(obj => obj.id === id) || [])
to each value in idArray
. The purpose of this function is unclear, as it returns an empty array if no matching object is found.Pros and Cons
Here's a brief analysis of the two approaches:
Filter (Array.prototype.filter())
Pros:
Cons:
FlatMap (Array.prototype.flatMap())
Pros:
Cons:
Library Usage
In both test cases, no external libraries are used. However, it's worth noting that flatMap() was introduced in ECMAScript 2019 (ES10) as a part of the standard library.
Special JS Feature or Syntax
There are no special JavaScript features or syntax mentioned in the benchmark definition. Both filter()
and flatMap()
are built-in methods on arrays, and their usage is straightforward.
Other Alternatives
If you need to filter an array, other alternatives besides Array.prototype.filter()
include:
filter
functionIf you need to flatten an array, other alternatives besides Array.prototype.flatMap()
include:
map
and flatten
functionsKeep in mind that these alternatives may have different performance characteristics or require additional setup.