var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var b = new Set(a)
return a.includes(3)
return b.has(3)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
includes | |
lookup |
Test name | Executions per second |
---|---|
includes | 26954134.0 Ops/sec |
lookup | 38090536.0 Ops/sec |
This benchmark compares the performance of two methods for checking if a particular value exists within a collection: using Array.includes()
for arrays and Set.has()
for sets, specifically with a predefined dataset of integers.
3
is present in an array a
which contains numbers from 1 to 10.3
is present in a Set
b
that was created from the same array.Array.includes()
Set.has()
Set
, as it must store each unique item and its associated hash.In this benchmark, no external library is used; it relies purely on native JavaScript features. Both Array
and Set
are built-in JavaScript objects, and their methods includes()
and has()
are part of standard ECMAScript functionality.
Manual Iteration: Instead of using Array.includes()
, one could manually iterate over the elements of an array using a loop. While this could offer slight flexibility (e.g., for custom equality checks), it would still be O(n) and generally less readable.
Other Data Structures: Consider using other data structures like Maps or Typed Arrays based on specific use cases. Maps would allow for key-value pair storage, yet for simple existence checks, Sets remain the most efficient.
Filtered Array: Instead of utilizing includes()
, one could filter the array to find if the value exists. However, this returns an array of matches and is more costly performance-wise (O(n)).
The benchmark demonstrates a performance contrast between using an array with linear search and a set with constant-time searching capability. In scenarios where you frequently need to check for the presence of elements within collections, using a Set
is generally more efficient, especially as the size of the dataset grows. Understanding these differences can help software engineers choose the appropriate data structures based on performance needs.