var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var b = new Set(a)
return a.includes(9)
return b.has(9)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Includes | |
lookup |
Test name | Executions per second |
---|---|
Includes | 11692820.0 Ops/sec |
lookup | 11098887.0 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The test compares the performance of two approaches: Array.prototype.includes()
and Set.prototype.has()
. Both methods are used to check if an element exists in a dataset (array or set, respectively).
Options Compared
Array.prototype.includes()
: This method checks if a specific value (9
in this case) is present in the array.Set.prototype.has()
: This method checks if a specific value (9
) is present in the set.Pros and Cons of Each Approach
Array.prototype.includes()
:Set.prototype.has()
for large datasets because it needs to iterate over the entire array to find the element.Set.prototype.has()
: Array.prototype.includes()
for large datasets because it uses a data structure (hash table) that allows for efficient lookups. It's also more memory-efficient than arrays.Set
object, which may not be available in older browsers.Library and Its Purpose
In this benchmark, the Set
library is used to create a set from an array (var b = new Set(a)
). The Set
object is a data structure that stores unique values, allowing for efficient lookups using the has()
method.
Special JavaScript Feature or Syntax
This benchmark uses a standard JavaScript feature: arrays and sets. No special syntax or features are required to run this benchmark.
Other Alternatives
If you want to test alternative approaches, here are a few options:
indexOf()
instead of includes()
: This will add an additional comparison step, making it slower than includes()
.Keep in mind that these alternatives are more complex and may not be representative of real-world use cases. The comparison between includes()
and has()
is a simple and straightforward way to demonstrate the performance difference between these two methods.