function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function createRandomIntArray(minLength, maxLength) {
const length = getRandomInt(minLength, maxLength);
const randomArray = [];
for (let i = 0; i < length; i++) {
const randomInt = i;
randomArray.push(getRandomInt(0, maxLength));
}
return randomArray;
}
const minLength = 1000;
const maxLength = 1001;
var ids1 = createRandomIntArray(minLength, maxLength);
var ids2 = createRandomIntArray(minLength, maxLength);
var ids3 = createRandomIntArray(minLength, maxLength);
var target1 = createRandomIntArray(1, 50);
var target2 = createRandomIntArray(1, 50);
var target3 = createRandomIntArray(1, 50);
var idsSet1 = new Set(ids1)
target1.some(id => idsSet1.has(id))
var idsSet2 = new Set(ids2)
target2.some(id => idsSet2.has(id))
var idsSet3 = new Set(ids3)
target3.some(id => idsSet3.has(id))
target1.some(id => ids1.includes(id))
target2.some(id => ids2.includes(id))
target3.some(id => ids3.includes(id))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
set | |
array |
Test name | Executions per second |
---|---|
set | 13070.4 Ops/sec |
array | 1647945.2 Ops/sec |
Let's break down the provided benchmark and its options.
Benchmark Definition
The benchmark is testing two different approaches to check if an element exists in an array:
some()
method with a callback function that checks for existence in a Set
object created from the original array (set
option).includes()
method on the original array itself (array
option).Options Comparison
Here's a comparison of the two options, including their pros and cons:
Set
object to quickly check if an element exists in the array.Set
operations are O(1) on average.Set
object.Set
object.includes()
method on the original array itself to check if an element exists.Library and Purpose
The Set
object is a built-in JavaScript library that provides a fast and efficient way to store unique values. In this benchmark, it's used to quickly check if an element exists in the original array by creating a new Set
object from the array and then checking for existence using the some()
method.
Special JS Feature or Syntax
In this benchmark, we're using the following JavaScript features:
id => idsSet1.has(id)
)."var idsSet1 = new Set(ids1)\r\n..."
).These features are widely supported in modern browsers and are a part of the ECMAScript 2015 standard.
Alternatives
If you were to use alternative approaches for this benchmark, some options could be:
Map
object instead of Set
to store the original array.However, these alternatives may not provide significant performance benefits over the current implementation and may add additional complexity.