var empty = { id: '', number: 10000 };
var array1 = [empty];
var array2 = [empty];
var entities = { '': empty };
var id = '';
for (let i = 0; i < 10000; i++) {
id = String(i);
entities[id] = { id, number: i }
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}
for (let i = 0; i < 100; i++) {
array1.push(entities[getRandomInt(i, 10000)]);
}
for (let i = 0; i < 100; i++) {
array2.push(entities[getRandomInt(i, 10000)]);
}
var data = Array.from(new Set([array1, array2])).reduce(
(acc, item) => {
if (array1.includes(item)) {
if (array2.includes(item)) {
acc.union.push(item);
} else {
acc.lhsOnly.push(item);
}
} else {
acc.rhsOnly.push(item);
}
return acc;
},
{ rhsOnly: [], lhsOnly: [], union: [] }
);
console.log(data)
var lMap = new Map(array1.map((item) => [item, true]));
var rMap = new Map(array2.map((item) => [item, true]));
var unionMap = new Map([lMap.entries(), rMap.entries()]);
var result = { rhsOnly: [], lhsOnly: [], union: [] };
for (var [item] of unionMap) {
if (lMap.has(item)) {
if (rMap.has(item)) {
result.union.push(item);
} else {
result.lhsOnly.push(item);
}
} else {
result.rhsOnly.push(item);
}
}
console.log(result)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.includes | |
Map.has |
Test name | Executions per second |
---|---|
Array.includes | 16672.3 Ops/sec |
Map.has | 21708.9 Ops/sec |
The provided JSON represents two JavaScript microbenchmarks, each testing the performance of different approaches for finding the union of arrays with duplicates. Here's an explanation of what is being tested and the pros and cons of each approach:
Benchmark Definition
The benchmark definition involves creating large arrays array1
and array2
, each containing 10,000 elements with unique IDs. A map entities
is created to store these elements with their corresponding IDs.
Two test cases are defined:
includes()
method to check if an element exists in an array.has()
method of a Map object to check if a key (element) exists in the map.Approaches Compared
The two approaches compared are:
includes()
method.Pros and Cons of Each Approach
Library Used
The Map
object is used in the Map.has test case. The purpose of this library is to provide a data structure that stores key-value pairs in a way that allows for fast lookups and insertions.
Special JavaScript Feature or Syntax
There are no special JavaScript features or syntax used in these benchmarks, aside from the use of arrow functions (() => { ... }
) and template literals (${...}
).
Other Considerations
When evaluating the performance of these two approaches, it's essential to consider the following factors:
In general, the Map.has approach is expected to perform better for large datasets, while the Array.includes approach may be more suitable for smaller datasets or when memory usage needs to be minimized.