var arr = ['1', 2, '3'];
arr.includes('3');
arr.indexOf('3') >= 0
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
includes | |
indexOf |
Test name | Executions per second |
---|---|
includes | 10240708.0 Ops/sec |
indexOf | 9262231.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
Benchmark Definition
The benchmark is comparing two approaches to check if an element exists in an array:
arr.includes('3')
arr.indexOf('3') >= 0
Script Preparation Code
var arr = ['1', 2, '3'];
This code creates a sample array arr
containing three elements.
Options Compared
The two options being compared are:
true
if the specified element is found in the array, and false
otherwise.Pros and Cons
includes()
for large arrays, as it stops iterating once it finds the first match or reaches the end of the array.Library Used
None in this benchmark. Both options are built-in JavaScript methods.
Special JS Feature/Syntax
None mentioned in this benchmark.
Other Alternatives
For checking if an element exists in an array, you can also use:
in
: This operator returns a boolean value indicating whether the specified property (or key) is present in the object.find()
, findIndex()
: These methods return the first element that matches the provided function or predicate.Benchmark Preparation Code
The code preparation section provides the initial setup for the benchmark, creating a sample array arr
and making it available to both test cases.
Individual Test Cases
Two test cases are defined:
These test cases measure the performance of each approach individually.
Latest Benchmark Result
The provided result shows the execution count per second for each test case, indicating how many times each operation was executed in a given time frame.
In summary, this benchmark compares two approaches to check if an element exists in an array: includes()
and indexOf() >= 0
. While both methods have their pros and cons, includes()
is often preferred due to its simplicity but may be slower for large arrays. The benchmark provides valuable insights into the performance of these operations on various devices and browsers.