var a = ['www.startpage.com/do/metasearch.pl?q=foo+bar', 'www.startpage.com', 'en.m.wikipedia.org/wiki/AppleScript', 'developer.mozilla.com'];
var b = a.find(item => item === 'developer.mozilla.com');
var a = ['www.startpage.com/do/metasearch.pl?q=foo+bar', 'www.startpage.com', 'en.m.wikipedia.org/wiki/AppleScript', 'developer.mozilla.com'];
var b = a.some(item => item === 'developer.mozilla.com');
var a = ['www.startpage.com/do/metasearch.pl?q=foo+bar', 'www.startpage.com', 'en.m.wikipedia.org/wiki/AppleScript', 'developer.mozilla.com'];
var b = a.includes('developer.mozilla.com');
var a = ['www.startpage.com/do/metasearch.pl?q=foo+bar', 'www.startpage.com', 'en.m.wikipedia.org/wiki/AppleScript', 'developer.mozilla.com'];
var b = a.indexOf('developer.mozilla.com');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array find | |
array some | |
array includes | |
array indexOf |
Test name | Executions per second |
---|---|
array find | 50682184.0 Ops/sec |
array some | 48196384.0 Ops/sec |
array includes | 48240876.0 Ops/sec |
array indexOf | 43502056.0 Ops/sec |
Let's break down what's being tested in the provided JSON.
The benchmark is testing four different ways to check if an element exists in an array:
Array.prototype.find()
: Returns the first element that satisfies the provided condition.Array.prototype.some()
: Returns a boolean indicating whether at least one element in the array satisfies the provided condition.Array.prototype.includes()
: Returns a boolean indicating whether the specified value is present in the array.Array.prototype.indexOf()
: Returns the index of the first occurrence of the specified value in the array.Now, let's discuss the pros and cons of each approach:
1. Array.prototype.find():
Pros:
some()
or includes()
, which can be beneficial for readability.Cons:
some()
and includes()
return a boolean value.2. Array.prototype.some():
Pros:
find()
when no match is found, as it can stop traversing the array immediately.Cons:
find()
.3. Array.prototype.includes():
Pros:
Cons:
4. Array.prototype.indexOf():
Pros:
includes()
.Cons:
Now, let's discuss special considerations and libraries used in the benchmark:
The test cases use var
declarations with arrow functions (=>
) for simplicity. There are no notable libraries being used in these examples.
Some special JavaScript features used here include:
=>
)Keep in mind that modern JavaScript development often focuses on more recent features like classes, modules, and async/await.
As for alternatives, other methods to check if an element exists in an array include:
for...of
loop or forEach()
with a callback functionArray.prototype.includes()
with the same syntax as shown in the benchmark (e.g., a.includes('developer.mozilla.com')
)These alternatives may offer varying trade-offs in terms of performance, readability, or convenience.