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('sausage')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Includes | |
Object[key] | |
Set.has(key) |
Test name | Executions per second |
---|---|
Includes | 15497112.0 Ops/sec |
Object[key] | 14744717.0 Ops/sec |
Set.has(key) | 15518599.0 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Definition JSON
The provided JSON defines a benchmark that compares the performance of three different approaches to check if an array contains a value:
array.includes('sausage')
obj['sausage']
(using object key lookup)set.has('sausage')
(using a Set data structure)Script Preparation Code
The script preparation code creates a large object (obj
) with 1000 properties, where each property has a random key and value. The keys are stored in an array (array
), which is then converted to a Set (set
). This setup ensures that the benchmark focuses on the performance of these specific operations.
Options Compared
The three test cases compare the following options:
includes
: checks if a value exists in an array using the includes
method.Object[key]
: uses object key lookup to access a property by its string representation (in this case, 'sausage'
).Set.has(key)
: uses the has
method of a Set data structure to check if a key is present.Pros and Cons
Here's a brief summary of each approach:
array.includes('sausage')
:obj['sausage']
(Object Key Lookup):set.has('sausage')
(Set Data Structure):Library/Functionality Used
None of these test cases use a specific library or framework. However, it's worth noting that the includes
method is a built-in method in JavaScript arrays, so no external library is required.
Special JS Features/Syntax
There are no special JS features or syntax used in this benchmark. All three approaches rely on standard JavaScript language constructs.
Other Alternatives
For larger datasets or more complex scenarios, alternative approaches might include:
includes
for large arrays.includes
.Array.prototype.find()
or Set.prototype.has()
might be available for even faster performance.Keep in mind that the specific approach chosen will depend on the use case and requirements of the application.