const arr = [];
for (let i = 0; i < 10000; i++) {
const n = 10 * Math.random();
arr.push(Math.floor(n));
}
const set = new Set(arr);
const arr2 = [];
for (let i = 1; i <= 100; i++) arr2.push(i);
const testArr = arr2.filter(el => arr.find(e => e === 5));
const testSet = arr2.filter(el => set.has(5));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array find | |
new Set has |
Test name | Executions per second |
---|---|
array find | 406889.0 Ops/sec |
new Set has | 181519.1 Ops/sec |
The benchmark defined in the provided JSON compares two methods for checking the presence of a number (specifically the number 5) in an array. The benchmark tests two approaches:
Using the .find()
Method:
arr.find(e => e === 5)
within an array filter on arr2
. Here, .find()
iterates through the arr
array (which contains 10,000 random numbers) to locate the first occurrence of the number 5 and returns that value if found, or undefined
if not found.Using a Set
with .has()
:
arr
into a Set (set = new Set(arr)
). Then, it checks if the number 5 exists in the Set with set.has(5)
. The Set data structure provides an efficient way to determine existence, as it uses a hash table internally.Using .find()
Method:
Using a Set
with .has()
:
Set.has()
has an average time complexity of O(1) due to the hash table implementation..find()
method significantly:new Set has
: 1,951,830.375 executions per second.array find
: 1,184,509.375 executions per second.The results showcase that the Set approach is nearly 65% faster than using the .find()
method, particularly evident given larger input sizes.
Using a plain loop: Instead of .find()
, a simple for
loop could iterate through arr
, checking for the number 5. This approach is similar in performance to .find()
, with O(n) complexity.
Binary Search: If the array is sorted, a binary search could be used, allowing for O(log n) complexity. However, this requires additional steps to sort the array first—introducing O(n log n) complexity for initial sorting.
Other Data Structures: Besides Set
, using a Map
could allow similar checks and can also provide additional data handling capabilities if needed.
In conclusion, the benchmark effectively demonstrates how different data structures and methods can lead to significant performance differences in JavaScript, particularly when handling larger datasets. The findings endorse the use of Sets for existence checks as a robust practice for efficiency in performance-sensitive applications.