const referenceArray = [
{id:1},{id:2},{id:3},{id:4},{id:5},{id:6},{id:7},{id:8},{id:9},{id:0}
];
const inputArray = [
{id:5},{id:1},{id:10},{id:9},{id:5},{id:2},{id:17},{id:0},{id:4},{id:0}
];
inputArray.map(inp => ({inp, isExisting: referenceArray.some(refA => refA.id === inp.id)}));
const referenceArray = [
{id:1},{id:2},{id:3},{id:4},{id:5},{id:6},{id:7},{id:8},{id:9},{id:0}
];
const inputArray = [
{id:5},{id:1},{id:10},{id:9},{id:5},{id:2},{id:17},{id:0},{id:4},{id:0}
];
const x = referenceArray.reduce((mapI, inp) => mapI.set(inp.id,inp), new Map());
inputArray.map(inp => ({inp, isExisting: x.has(inp.id)}));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array some | |
Map has |
Test name | Executions per second |
---|---|
Array some | 5902883.5 Ops/sec |
Map has | 2621569.0 Ops/sec |
Let's break down the provided benchmark and its test cases.
Benchmark Definition JSON
The benchmark definition is quite straightforward, which represents two different approaches to check if an element exists in an array or map:
Array some
: This approach uses the some()
method on the input array to check if any element matches a condition (in this case, the existence of an element with the same id
in the reference array).Map has
: This approach uses the has()
method on a Map object to check if a key (element's id
) exists.Options Compared
The two approaches being compared are:
some()
method on an arrayhas()
method on a MapPros and Cons of Each Approach:
Map has
because it requires scanning the entire array.Array some
, especially when dealing with large datasets.Library or Special JS Feature
In this benchmark, no special JavaScript features or libraries are used beyond the standard Map
and Array
types. However, if we consider the some()
method as a part of the standard library, it's still an interesting aspect to explore in terms of performance.
Other Considerations
When dealing with large datasets, the performance difference between these two approaches can be significant. In general:
some()
might be a good choice.has()
is usually a better option.Alternatives
Other alternatives for this kind of benchmark include:
every()
, find()
, or includes()
.For this particular benchmark, measuring the performance difference between using some()
and Map has
provides valuable insights into how JavaScript engines handle array and map operations.