var array = Array.from(Array(5), (x, index) => index + 1).sort(() => 0.5 - Math.random());
var set = new Set(array);
for (let i = 0; i < array.length; i++) {
array.includes(i);
}
for (let i = 0; i < array.length; i++) {
set.has(i);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array Includes | |
Set Has |
Test name | Executions per second |
---|---|
Array Includes | 1040616.2 Ops/sec |
Set Has | 1000978.1 Ops/sec |
Let's break down the provided JSON benchmark definition and test cases.
Benchmark Definition
The benchmark is designed to compare the performance of two JavaScript methods: Array.includes()
and Set.has()
. The purpose of this benchmark is to determine which method is more efficient for checking if an element exists in a given array or set.
Script Preparation Code
The script preparation code generates a random array of numbers from 0 to 4 (inclusive) and sorts it. This array will be used as the input data for both Array.includes()
and Set.has()
. The sorting is done using a subtle trick: (() => 0.5 - Math.random())
creates an unpredictable order, which helps to avoid optimizations that might favor one method over the other.
Html Preparation Code
The html preparation code is empty, indicating that no HTML elements are involved in this benchmark.
Individual Test Cases
There are two test cases:
array.includes(i)
for each element.set.has(i)
for each element.Library Used
In this benchmark, the Array.from()
method is used to create an array from an iterable (in this case, a callback function that generates numbers). The Set
class is also used to create a new set from the array.
Special JS Feature/Syntax
None are mentioned in this benchmark. However, it's worth noting that the use of Array.from()
and Set
is a modern JavaScript feature that was introduced in ECMAScript 2015 (ES6).
Pros and Cons of Different Approaches
Here's a brief analysis of the two approaches:
Set.has()
tends to perform better due to its O(1) average time complexity, making it more efficient for lookup operations.Other Alternatives
If you wanted to explore alternative approaches, here are a few:
Array.includes()
. However, this would likely be slower than both Array.includes()
and Set.has()
.nativeArray.includes()
or Set.prototype.has()
(if available) for improved performance.Keep in mind that these alternatives might have their own trade-offs in terms of compatibility, maintainability, and optimization opportunities.