var data = [Array(10000)].map((_, i) => [i, i]);
var cachedArray = ['a', 'b', 'c', 'd', 'e', 'f'];
var g = 'g';
data.forEach(() => {
return ['a', 'b', 'c', 'd', 'e', 'f'].includes(g);
});
data.forEach(() => {
return cachedArray.includes(g);
});
data.forEach(() => {
return 'a' === g || 'b' === g || 'c' === g || 'd' === g || 'e' === g || 'f' === g;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.includes | |
Array.includes (cached array) | |
OR operator |
Test name | Executions per second |
---|---|
Array.includes | 11631.1 Ops/sec |
Array.includes (cached array) | 12453.5 Ops/sec |
OR operator | 270998.5 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and analyzed.
Benchmark Definition
The test case is designed to compare the performance of two approaches: using Array.includes()
with a cached array, and using an OR operator (||
) to check for membership in an array. The goal is to determine which approach is more performant.
Script Preparation Code
The script prepares an array data
with 10,000 elements, each containing a value from the string 'a'
to 'f'
. A cached array cachedArray
is also created with the same values as data
.
Html Preparation Code There is no HTML preparation code provided.
Individual Test Cases
Array.includes()
with a dynamic value g
which is assigned to 'a'
. The script iterates over an array of 10,000 elements using the forEach()
method and checks if each element's first value (using data[i][0]
) includes g
.Array.includes()
with a cached array cachedArray
containing the same values as data
. The script iterates over an array of 10,000 elements using the forEach()
method and checks if each element's first value includes g
.||
) to check for membership in an array with dynamic values. The script iterates over an array of 10,000 elements using the forEach()
method and checks if any of the values match g
.Library Used
There is no explicit library mentioned in the benchmark definition or test cases. However, it's worth noting that Array.includes()
is a built-in JavaScript method.
Special JS Features/ Syntax The benchmark makes use of several features:
() => { ... }
) to define small anonymous functions.[i, i]
) to create arrays with dynamic values.g
which is later used as a string literal.Pros and Cons of Different Approaches
Array.includes()
with a cached array due to its iterative nature.Other Alternatives If you're interested in exploring alternative approaches, here are a few options:
/g
flag) to search for a value in an array.Keep in mind that these alternatives might not provide the same performance benefits as Array.includes()
with a cached array or the OR operator approach.