var array = [];
for (var i = 0; i < 10000; i++) {
array.push({value: { value: Math.floor(Math.random() * 1000)}});
}
array.push({value: { value: 42}});
var tempResult = array.some(v => v.value.value === 42)
var tempResult = array.filter(v => v.value.value === 42);
var tempResult = array.indexOf({value: {value: 42}}) > -1;
var tempResult = array.includes(v => v.value.value === 42);
var tempResult = array.find(v => v.value.value === 42);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.some | |
Array.filter | |
Array.indexOf | |
Array.includes | |
Array.find |
Test name | Executions per second |
---|---|
Array.some | 2136128.2 Ops/sec |
Array.filter | 21674.8 Ops/sec |
Array.indexOf | 194630.0 Ops/sec |
Array.includes | 9053109.0 Ops/sec |
Array.find | 1116909.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
The provided benchmark compares four different methods for searching for a value within an array in JavaScript:
some()
filter()
indexOf()
includes()
(new in ECMAScript 2019)Options Compared:
some()
: Returns true
if at least one element passes the provided test.filter()
: Creates a new array with all elements that pass the provided test.indexOf()
: Returns the index of the first occurrence of the specified value in the array. If the value is not found, it returns -1.includes()
: Returns true
if the array includes the element at the specified index.Pros and Cons:
true
or false
, which might not be what you want if the method is expected to return an index or valuetrue
or false
, which might be what you want in some casesLibrary/Functionality Descriptions:
Special JavaScript Feature/Syntax (if applicable): None explicitly mentioned.
Other Considerations:
indexOf()
might be the best choice. However, if you want to stop as soon as you find a match and return true
or false
, some()
could be a better option.filter()
can be more efficient since it only iterates over the elements that match the test.includes()
method is generally fast and efficient but might not be as expressive as other methods.Alternatives:
forEach()
: Iterates over each element in the array, which can be useful if you need to perform some operation on each match.map()
: Creates a new array with the results of applying the provided function on each element in the original array. This might not be what you want if you're just looking for a specific value within the array.In conclusion, when choosing a method for searching within an array in JavaScript, consider your specific requirements and choose the most suitable option based on factors such as performance, expressiveness, and readability.