var n = 1000;
var a = [Array(n)].map(() => Math.floor(Math.random()*n));
var b = new Set(a);
var t = a[Math.floor(n/2)];
return a.includes(t);
return b.has(t);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
includes | |
has |
Test name | Executions per second |
---|---|
includes | 1909932.9 Ops/sec |
has | 10183305.0 Ops/sec |
I'd be happy to explain the JavaScript microbenchmark being tested on MeasureThat.net.
Benchmark Overview
The benchmark is designed to compare the performance of two different methods for checking if an element exists in an array: includes()
and has()
. The benchmark creates a large array of random numbers, converts it to a Set data structure, and then uses each method to search for a specific middle value in the array.
What's being tested
The benchmark is testing the performance difference between using the includes()
method versus the has()
method on arrays. Specifically, it measures how many times each method can execute per second (ExecutionsPerSecond) across different browsers and devices.
Options compared
The two methods being compared are:
includes()
: This method checks if a specified value (t
) exists in an array by iterating through the elements of the array until it finds a match.has()
: This method is not a built-in JavaScript method, but rather a custom implementation that uses a Set data structure to store the unique values in the array.Pros and Cons
includes()
: Pros:has()
for very large arrays due to the iteration required to find the element.has()
: Pros:includes()
for large arrays, as it uses a Set data structure to quickly check for existence.
Cons:Library/Functionality
The custom implementation of has()
is likely using a Set data structure (b
) created from the original array (a
). When checking if an element exists using has()
, it simply checks if the value to be searched for (t
) is present in the set. This allows for efficient lookup times.
Special JS Feature/Syntax
There are no special JavaScript features or syntax used in this benchmark beyond what's necessary to demonstrate the comparison between includes()
and has()
methods.
Alternative approaches
Other alternatives for checking if an element exists in an array could include:
has()
, but with improved performance optimizations._.contains()
function.Keep in mind that the specific choice of implementation will depend on the use case, performance requirements, and personal preference.