var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
return a.includes(9)
var b = new Set(a);
return b.has(9)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
includes | |
lookup |
Test name | Executions per second |
---|---|
includes | 60132956.0 Ops/sec |
lookup | 4128059.2 Ops/sec |
The benchmark defined in the provided JSON tests the performance of two different methods for checking if a value exists in a collection: using an array's includes
method and a Set
's has
method. The benchmark aims to compare the efficiency of these two approaches in terms of execution speed.
Array's includes
Method:
return a.includes(9)
includes
Set's has
Method:
var b = new Set(a); return b.has(9)
lookup
Set
. A Set
is a built-in JavaScript object that allows the storage of unique values, enabling quick lookups, typically on average in constant time, as it is implemented using a hash table.includes
Method:Pros:
Cons:
has
Method:Pros:
Cons:
Set
from the array before performing lookups.Set
, especially if the dataset is small or lookups are infrequent.Set
might not justify its use.includes
method achieved approximately 41,927,184 executions per second, while the has
method resulted in about 3,890,894 executions per second. This suggests that despite the speed of straightforward usage for includes
, the performance degradation at scale should be considered.Set
, developers should be aware of the initial overhead incurred from creating the Set
from the array, which could affect performance in cases where this operation occurs frequently or is done in a tight loop.Some alternative approaches to consider include:
Using an Object for Lookup: Instead of a Set
, one could use a plain object to store keys and check for existence. This can also provide average constant time complexity for lookups.
Array.prototype.indexOf(): An older method which can also check for existence but performs similarly to includes
(linear complexity).
Binary Search on Sorted Arrays: If the array can be maintained in a sorted state, binary search can be employed for faster lookups (O(log n)), though this requires additional complexity in managing the sorted order with insertions and deletions.
Choosing between these options will depend on the specific use case, including the expected size of the dataset and the frequency of membership checks required.