<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var arr = _.times(8000, n => `elem_${n}`);
var se = new Set(arr)
arr.includes('elem_7999')
se.has('elem_7999')
var converted = new Set(arr);
converted.has('elem_7999');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
includes | |
has | |
convert to set before includes |
Test name | Executions per second |
---|---|
includes | 88400.0 Ops/sec |
has | 23626614.0 Ops/sec |
convert to set before includes | 5683.4 Ops/sec |
Overview
The provided benchmark measures the performance of three different approaches to check if an element exists in an array or set: arr.includes('elem_7999')
, se.has('elem_7999')
, and converting the array to a set (converted = new Set(arr)
) before checking.
Options Compared
arr.includes('elem_7999')
: This approach checks if an element with the specified value exists in the original array.se.has('elem_7999')
: This approach uses the Set
data structure to check if an element exists.converted = new Set(arr); converted.has('elem_7999')
: This approach converts the array to a set, which allows for faster lookups.Pros and Cons
arr.includes('elem_7999')
:se.has('elem_7999')
:arr.includes()
, as sets use hash tables internally.Set
object, which may not be necessary in all cases.converted = new Set(arr); converted.has('elem_7999')
:Library and Purpose
The benchmark uses Lodash's _.times()
function to generate an array of 8000 elements. The Set
data structure is used to provide fast lookups.
Special JS Feature/Syntax
None mentioned in the provided benchmark definition, but it's worth noting that using Set.has()
can be a shorthand for creating a new set and then checking its existence.
Other Alternatives
Array.prototype.indexOf()
: This approach would search for the element by index, which may not be as efficient as using includes()
.Binary Search
: For sorted arrays, binary search can provide significant performance improvements over linear searches.Map
, could potentially offer better lookup times than sets.In summary, the benchmark provides valuable insights into the performance differences between these three approaches for checking if an element exists in an array or set.