var array = [1, 2, 3, 100500, 666]
array.indexOf(666) !== 1
array.includes(666)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
IndexOf | |
Includes |
Test name | Executions per second |
---|---|
IndexOf | 66621932.0 Ops/sec |
Includes | 57975860.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition and Script Preparation Code
The benchmark definition represents two test cases: IndexOf
and Includes
. The script preparation code provides an array of numbers, which is used as input for both tests. The code is simple and straightforward, making it easy to understand.
var array = [1, 2, 3, 100500, 666];
Test Cases: IndexOf vs Includes
The two test cases compare the performance of two JavaScript methods:
indexOf()
: This method returns the index of the specified value in the array. If the value is not found, it returns -1
.includes()
: This method returns a boolean indicating whether the specified value is present in the array.Comparison and Pros/Cons
Both methods have their strengths and weaknesses:
indexOf()
is generally faster because it only needs to traverse the array until it finds the target value or reaches the end of the array.-1
when not found, which might be unnecessary for some use cases.includes()
is more intuitive and often preferred due to its concise syntax.indexOf()
due to the additional overhead of returning a boolean.Library Usage
There is no explicit library mentioned in the benchmark definition. However, it's worth noting that both indexOf
and includes
are built-in methods in JavaScript, so no external libraries are required.
Special JS Feature or Syntax
There is no special JavaScript feature or syntax explicitly used in this benchmark. The code is straightforward and uses standard JavaScript constructs.
Other Alternatives
If you need to optimize array searches, consider the following alternatives:
findIndex()
: Similar to indexOf
, but returns the index of the first matching element instead of just checking for presence.For more advanced optimizations or comparisons, MeasureThat.net provides a wide range of benchmarking options and scripts. You can explore these further to find the best approach for your specific needs.