[1,2, 3, 4, 5].indexOf(4) !== -1
[1,2, 3, 4, 5].filter(a=> a ===4).length > 0
[1,2, 3, 4, 5].find(a => a === 4) !== undefined
[1,2, 3, 4, 5].some( a => a === 4)
![1,2, 3, 4, 5].every( a => a !== 4)
[1,2, 3, 4, 5].lastIndexOf(4) !== -1
[1,2, 3, 4, 5].includes(4)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
indexOf !== | |
filter length > 0 | |
find !== undefined | |
some | |
! every | |
lastIndexOf !== -1 | |
includes |
Test name | Executions per second |
---|---|
indexOf !== | 81824208.0 Ops/sec |
filter length > 0 | 27621836.0 Ops/sec |
find !== undefined | 5076108.5 Ops/sec |
some | 167872016.0 Ops/sec |
! every | 161710352.0 Ops/sec |
lastIndexOf !== -1 | 48612192.0 Ops/sec |
includes | 776728896.0 Ops/sec |
Measuring the performance of JavaScript array operations is crucial for optimizing code and improving application performance.
What's being tested?
The benchmark tests six different ways to check if an element exists in an array:
indexOf
method returning a non-negative valuefilter
find
some
every
includes
methodOptions compared
The benchmark compares two main approaches for each test case:
indexOf
, filter
, find
, some
, and includes
.Pros and Cons of each approach
Here's a brief summary of the advantages and disadvantages of each approach:
Traditional Approach (Explicit Loop)
Pros:
Cons:
Modern Approach (Built-in Methods)
Pros:
Cons:
Other considerations
When choosing an approach, consider the following factors:
For example, using includes
might be more readable than implementing a custom search function.
Library or special JS feature
The benchmark uses JavaScript's built-in array methods, such as indexOf
, filter
, find
, some
, and includes
. These methods are part of the ECMAScript standard and have been implemented by various browsers to provide consistent behavior across different environments.
There is no specific library or special JS feature used in this benchmark. The focus is on measuring the performance of the built-in array methods themselves.
Alternatives
Other alternatives for checking array element existence could be:
for
loop with indexingincludes
method)However, these approaches are not typically used in production code due to performance considerations and the availability of optimized built-in methods.