var obj = (new Array(1000)).fill(null).reduce((prev, newVal) => {prev[Math.random() + ''] = Math.random() + ''; return prev; }, { sausage: 'tst' });
var array = Object.keys(obj);
var set = new Set(array);
array.includes('sausage')
obj['sausage']
set.has('saudage')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Includes | |
Object[key] | |
Set.has |
Test name | Executions per second |
---|---|
Includes | 207865344.0 Ops/sec |
Object[key] | 175639600.0 Ops/sec |
Set.has | 280120928.0 Ops/sec |
I'll break down the provided benchmark and explain what's being tested.
Benchmark Definition JSON
The benchmark definition represents three different ways to check if an array contains a specific value:
Set.has('sausage')
: This method checks if a Set object contains the string 'sausage'. A Set is an unordered collection of unique values.obj['sausage']
: This method accesses the property 'sausage' on the obj
object, which is created by reducing an array with null values and adding random keys. This approach relies on object key lookups.array.includes('sausage')
: This method checks if the string 'sausage' exists in the array
. The array contains a large number of unique random strings.Options Compared
The benchmark compares three different approaches:
obj['sausage']
). This approach relies on object key lookups, which can be slower than using a Set.array.includes()
method to check for membership in the array. This approach is generally faster than accessing individual elements of the array.Pros and Cons
Here are some pros and cons of each approach:
Library and Special JS Features
The benchmark uses a JavaScript library called YaBrowser/24 (Yandex Browser), which provides a specific implementation of WebKit-based browsing. There are no special JS features mentioned in this benchmark, so I won't discuss any further.
Other Alternatives
If you're looking for alternative ways to check if an array contains a value, you could consider using:
[...array].includes()
to check if an array contains a value.Keep in mind that these alternatives may have different performance characteristics and are not necessarily more efficient than the methods being compared in this benchmark.