var a = [];
for (var i = 0; i < 100000; i++) {
a.push(i);
}
var b = new Set(a)
return a.includes(99999)
return b.has(99999)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
includes | |
lookup |
Test name | Executions per second |
---|---|
includes | 5598.8 Ops/sec |
lookup | 9488280.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark is designed to compare the performance of two approaches: using Array.includes()
(test case "includes") versus using a Set
data structure (b.has()
) for fast membership testing. The test creates an array a
with 100,000 elements and then converts it into a set b
.
Comparison Options
There are two comparison options:
Array.includes()
: This method checks if a value exists in the array by iterating through each element until it finds a match or reaches the end of the array.Set.has()
: This method checks if a value exists in the set by using a hash table to store elements and then checking for membership.Pros and Cons
Array.includes()
:Set.has()
:Library and Purpose
In this benchmark, the Set
library is used to create a set data structure (b
) from an array (a
). The purpose of using a set here is to leverage its fast lookup times for membership testing.
Special JavaScript Feature or Syntax
There is no special JavaScript feature or syntax being tested in this benchmark. However, it's worth noting that sets are a built-in data structure in modern JavaScript and are widely supported across most browsers.
Other Alternatives
For fast membership testing, other alternatives to Array.includes()
and Set.has()
include:
Map.get()
: Similar to Set.has()
, but uses a map data structure instead of a set. Maps can be more memory-efficient than sets for large datasets.Array.prototype.indexOf()
or Array.prototype.lastIndexOf()
: These methods search for the first or last occurrence of a value in an array, respectively. They can be faster than Array.includes()
but may not be as efficient for very large arrays.Overall, this benchmark provides a useful comparison between two common approaches to fast membership testing in JavaScript, and it highlights the trade-offs between simplicity, memory usage, and performance.