<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var a = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19"];
a.indexOf("12") >= 0
a.includes("12")
a.includes((v) => v === "12")
a.find((v) => v === "12")
a.some((v) => v === "12")
a.filter((v) => v === "12").length > 0
for (var i = 0; i < a.length; i++) {
if (a[i] === "12") {
return true;
}
}
return false;
$.inArray("12", a)
_.includes(a, "12")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.indexOf() | |
Array.includes(value) | |
Array.includes(function) | |
Array.find() | |
Array.some() | |
Array.filter() | |
Loop | |
$.inArray() | |
_.includes() |
Test name | Executions per second |
---|---|
Array.indexOf() | 22717238.0 Ops/sec |
Array.includes(value) | 22887502.0 Ops/sec |
Array.includes(function) | 24451446.0 Ops/sec |
Array.find() | 24470694.0 Ops/sec |
Array.some() | 24621240.0 Ops/sec |
Array.filter() | 17567288.0 Ops/sec |
Loop | 1290532.2 Ops/sec |
$.inArray() | 9007255.0 Ops/sec |
_.includes() | 7978676.5 Ops/sec |
Measuring the performance of JavaScript array methods can be a complex task, as it depends on various factors such as the specific use case, data size, and browser or engine implementation.
The provided benchmark tests six different approaches to find an element in an array:
includes(value)
, but with a callback function that checks for equality.Here's a brief overview of each approach:
indexOf()
returns the index of the first occurrence, while includes(value)
returns a boolean indicating whether the value exists. The main difference is that indexOf()
will throw an error if the value is not found, whereas includes(value)
will return false.includes(value)
, but with a more flexible way of defining the condition.Now, let's analyze the results:
filter()
needs to create a new array and iterate over it.filter()
, with average execution times ranging from 10-50 nanoseconds.In general, the order of performance can be summarized as follows:
Keep in mind that these results are specific to the provided benchmarking setup and may vary depending on your use case and data size.
To optimize performance, consider the following best practices:
includes(value)
instead of indexOf()
if you don't need the index.includes(function)
if you need more control over the equality check.Array.filter()
unless it's absolutely necessary.Array.find()
or Array.some()
when you need to find the first or any element that meets a condition.By understanding the strengths and weaknesses of each method, you can choose the best approach for your specific use case.