var a = ['abc', 'def'];
var b = new Set(a)
return a.includes('def')
return b.has('def')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
includes | |
lookup |
Test name | Executions per second |
---|---|
includes | 201611408.0 Ops/sec |
lookup | 627682816.0 Ops/sec |
The benchmark defined in the provided JSON compares the performance of two methods for checking the existence of an element in a collection: using an array with the .includes()
method and using a Set
with the .has()
method in JavaScript. Below are details on the two approaches, their pros and cons, and other pertinent considerations.
Array.includes()
return a.includes('def')
true
if the value is found, otherwise it returns false
.Set.has()
return b.has('def')
Set
is a built-in JavaScript object that allows you to store unique values of any type. The .has()
method checks if a certain element exists in the Set
, returning true
if it does, or false
if it does not.Pros:
Cons:
Pros:
Cons:
Set
, which may not be justified for small arrays or collections with few elements.Set
.Use Cases:
.includes()
would suffice.Set
is highly recommended for better performance.Memory Usage:
Set
can use more memory due to its internal structure for fast access, in most scenarios, this trade-off is worth it considering the time efficiency it provides.Other Collections: Depending on the requirements, you could use objects (for key-value pairs) or Map objects for ordered collections with unique keys, but they may not fit the need for simple existence checks directly like Set
.
Libraries: For additional collection data types or utility functions, libraries like Lodash can help, but for basic existence checks, natively using arrays or sets is usually sufficient.
In summary, this benchmark provides valuable insights into the performance differences between using an array's .includes()
method and a Set
's .has()
method. For high-performance applications, especially with larger datasets, leveraging a Set
can lead to significant improvements in execution time.