var obj = (new Array(1000)).fill(null).reduce((prev, newVal) => {prev[Math.random() + ''] = Math.random() + ''; return prev; }, { });
var array = Object.keys(obj);
obj['sausage'] = 'tst';
array.push('sausage');
array.includes('sausage')
obj['sausage']
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Includes | |
Object[key] |
Test name | Executions per second |
---|---|
Includes | 15215021.0 Ops/sec |
Object[key] | 13872604.0 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, compared, and considered.
Benchmark Definition
The benchmark measures the performance of two approaches to check if an array contains a value:
array.includes('sausage')
obj['sausage']
Both approaches aim to find if the string "sausage" is present in the array or object respectively.
Script Preparation Code
The script preparation code generates a large array of 1000 objects, each containing random properties with keys and values. The code then:
Object.keys(obj)
).sausage
on the original object.This setup simulates a scenario where you might need to search for a specific value in an array or object, which is what the benchmark tests.
Options Compared
The two approaches being compared are:
array.includes('sausage')
: This method checks if the string "sausage" is present in the array by iterating over its elements and checking for a match.obj['sausage']
: This approach uses object key access to retrieve the value associated with the key "sausage".Pros and Cons
array.includes('sausage')
)Pros:
Cons:
obj['sausage']
)Pros:
Cons:
Library and Special JS Features
In this benchmark, the Object.keys()
method is used, which is a built-in JavaScript function that returns an array of an object's own enumerable property names. This is not a library per se but rather a native JavaScript feature.
There are no special JavaScript features mentioned in the provided code or benchmark definition.
Other Alternatives
If you're interested in exploring alternative approaches to this problem, here are a few examples:
Set
data structure: You can create a set from the array and check for membership using the has()
method. This approach is generally faster than iterating over an array.Map
data structure: Similar to sets, you can use a map to store unique values and then search for membership.Keep in mind that these alternatives might not be directly applicable to this specific benchmark or may have different performance characteristics depending on the use case.