var i = 0;
var a = [Array(1000).keys()];
var b = new Set(a);
i = Math.floor(Math.random() * 1000) + 1;
return a.includes(i);
i = Math.floor(Math.random() * 1000) + 1;
return b.has(i);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Includes Performance | |
Has Performance |
Test name | Executions per second |
---|---|
Includes Performance | 3097987.0 Ops/sec |
Has Performance | 22002604.0 Ops/sec |
The benchmark defined in the provided JSON tests the performance of two different methods used to check for the existence of a number in a list: using the Array.prototype.includes()
method and using the Set.prototype.has()
method. Both approaches offer distinct advantages and disadvantages depending on the use case.
a
): The line var a = [...Array(1000).keys()];
generates an array of integers from 0 to 999.b
): The line var b = new Set(a);
converts the array into a set. Sets in JavaScript store unique values and provide faster lookups compared to arrays.The benchmark comprises two individual test cases:
Includes Performance:
i = Math.floor(Math.random() * 1000) + 1; return a.includes(i);
i
(ranging from 1 to 1000) exists in the array a
using the includes()
method.includes()
method is straightforward and allows checking for existence of values in arrays, but it performs a linear search.Has Performance:
i = Math.floor(Math.random() * 1000) + 1; return b.has(i);
i
exists in the set b
using the has()
method.has()
method allows for average constant time complexity O(1) due to the underlying hash table implementation of sets, making it significantly faster for lookups in larger data sets.The benchmark results reveal the performance of each test case measured in executions per second:
This indicates that using a Set
for membership checks is vastly more efficient than using an array, particularly as the size of the dataset grows.
Memory Usage: While using a Set is quicker for lookups, it does consume more memory due to its internal structure. If memory usage is a critical factor, using an array might be more suitable for smaller datasets.
Mutability: Arrays are mutable and can contain duplicate entries. This may be beneficial if the order or duplicates matter for your application.
Other Data Structures: In environments where additional performance optimizations are required, developers may also consider data structures such as Maps or using libraries like Lodash which provide their own functionalities for efficient search and indexing.
Hybrid Approaches: Depending on the specific use case, a combination of both data structures may be beneficial. For smaller lists, using an array may suffice, but for larger datasets or performance-intensive applications, sets offer a clear advantage.
In summary, the comparison between using Array.includes()
and Set.has()
highlights the differences in their performance and use cases, steering developers towards choosing the appropriate method based on their application's requirements.