var obj = (new Array(1000)).fill(null).reduce((prev, newVal) => {prev[Math.random() + ''] = Math.random() + ''; return prev; }, { sausage: 'tst' });
var array = Object.keys(obj);
array.includes('sausage')
obj['sausage']
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Includes | |
Object[key] |
Test name | Executions per second |
---|---|
Includes | 93186936.0 Ops/sec |
Object[key] | 77884904.0 Ops/sec |
Let's break down the provided benchmark and its test cases.
Benchmark Overview
MeasureThat.net is testing the performance of two different approaches to check if an array contains a specific value: array.includes()
and accessing an object using its key (obj['sausage']
).
Script Preparation Code
The script preparation code generates a large array with 1000 random keys, where each key has a unique string value. The key is stored in the obj
variable.
var obj = (new Array(1000)).fill(null).reduce((prev, newVal) => {
prev[Math.random() + ''] = Math.random() + '';
return prev;
}, { sausage: 'tst' });
This code creates a large array and populates it with random keys using the reduce()
method. The key is stored in an object (not explicitly shown in the provided code).
Html Preparation Code
The HTML preparation code is empty, which means that no additional setup or rendering is required for this benchmark.
Test Cases
There are two test cases:
"array.includes('sausage')"
This test case uses the includes()
method to check if the array contains the string 'sausage'
.
"obj['sausage']"
This test case accesses the value associated with the key 'sausage'
in the obj
object.
Library and Purpose
The reduce()
method is a built-in JavaScript method used to apply a function to each element of an array and reduce it to a single output. In this benchmark, it's used to generate the random keys for the array.
Special JS Feature/Syntax
There are no special JavaScript features or syntaxes being tested in this benchmark. It only uses standard JavaScript methods and data structures.
Pros and Cons of Approaches
Other Alternatives
array.indexOf()
or array.lastIndexOf()
: These methods can also be used to check if an array contains a specific value, but they may have different performance characteristics depending on the browser and JavaScript engine.Array.prototype.some()
or Array.prototype.every()
: These methods can be used with callback functions to iterate over the array and check for the presence of a value.In summary, this benchmark is testing the performance of two simple yet distinct approaches to check if an array contains a specific value. The results will provide insight into how these different methods perform in various browsers and JavaScript engines.