var array = ['banana', 'sausage', 'jesus']
array.indexOf('sausage') !== 1
array.includes('sausage')
array.find(item => item === 'sausage')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
indexOf | |
Includes | |
find |
Test name | Executions per second |
---|---|
indexOf | 53176404.0 Ops/sec |
Includes | 49341968.0 Ops/sec |
find | 21930302.0 Ops/sec |
Let's break down the benchmark and analyze what's being tested.
What is being tested?
The provided JSON represents a microbenchmark that compares three different methods for searching an element within an array: indexOf
, includes
, and find
. Each test case measures the execution time of these methods on a specific input string ("sausage") in a given JavaScript array.
Options compared
indexOf
: A method that returns the index of the first occurrence of the specified value. If the value is not found, it returns -1
.includes
: A method that checks if the array includes the specified value without returning its index.find
: A method that finds the first element in the array that satisfies the provided condition.Pros and Cons
indexOf
: Pros: Simple and efficient for finding the exact index of an element. Cons: Returns -1
if not found, which can be misleading. Also, it only searches for a single value.includes
: Pros: Faster than indexOf
for larger arrays or when searching for multiple values. Cons: Returns true
or false
, but does not return the index.find
: Pros: More flexible and expressive than indexOf
, as it returns the actual element if found. Cons: Slower than both indexOf
and includes
due to its iterative search.Library and purpose
There is no library used in this benchmark. The methods being compared are built-in JavaScript methods, which means they are implemented natively by the JavaScript engine.
Special JS features or syntax
None mentioned.
Other alternatives
If you were to implement a custom solution for these search methods, some alternative approaches might include:
Array.prototype.some()
or Array.prototype.every()
to achieve similar results as includes
.find
.For example, an alternative implementation for indexOf
could involve using a binary search algorithm. However, given the simplicity and directness of the built-in methods, it's unlikely that a custom solution would offer significant performance improvements.
In summary, MeasureThat.net is testing the relative performance of three basic JavaScript array methods: indexOf
, includes
, and find
. The benchmark provides insight into which method is fastest for searching an element in an array under specific conditions.