var array = ['banana', 'sausage', 'jesus']
array.indexOf('sausage')
array.includes('sausage')
array.some(v => v === 'sausage')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
IndexOf | |
Includes | |
some |
Test name | Executions per second |
---|---|
IndexOf | 38673060.0 Ops/sec |
Includes | 43196696.0 Ops/sec |
some | 125027728.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and some pros/cons of each approach.
Benchmark Overview
The benchmark is comparing three different methods to check if an array contains a specific value: indexOf()
, includes()
, and some()
.
Library: None
There are no external libraries used in this benchmark. The array is created using JavaScript's built-in syntax.
Special JS Feature/Syntax: Some
The some()
method uses the "ternary operator" or "conditional expression" feature of JavaScript, which allows you to write a concise way to perform conditional checks. This feature is commonly used for short-circuit evaluations and can be an efficient way to stop evaluating expressions as soon as a condition is met.
Comparison
The three methods being compared are:
indexOf()
: This method returns the index of the first occurrence of the specified value in the array. If the value is not found, it returns -1.includes()
: This method returns a boolean value indicating whether the array includes the specified value or not.some()
: This method returns a boolean value indicating whether at least one element in the array satisfies the provided condition.Pros and Cons of Each Approach
indexOf()
:includes()
: indexOf()
for large arrays with unique values. It's also worth noting that includes()
was introduced in ECMAScript 2019 and might require polyfills for older browsers.some()
: Benchmark Result
The latest benchmark results show that:
some()
is the fastest execution method among the three, executing 125 million times per second.includes()
comes in second, with around 43 million executions per second.indexOf()
takes the longest time to execute, around 38.7 million executions per second.Keep in mind that these results are browser-specific and may vary depending on other factors like system resources, CPU architecture, and software configuration.
Other Alternatives
There are other methods to check if an array contains a specific value, such as:
filter()
: Returns an array of elements for which the provided function returns true.forEach()
: Executes the provided callback for each element in the array./regex/
): Can be used to search for patterns within arrays.However, these methods may not provide the same level of performance as indexOf()
or includes()
for simple checks. The choice of method depends on the specific use case and requirements.