<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var array = [6, 44, 542, 235, -26, 82, 235, 277, 643, 90, 777, 334, 41, 5, 98, 183];
array.indexOf(777) !== 1
array.includes(777)
_.includes(array, 777)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
IndexOf | |
Includes | |
lodash |
Test name | Executions per second |
---|---|
IndexOf | 41236116.0 Ops/sec |
Includes | 37556968.0 Ops/sec |
lodash | 12575131.0 Ops/sec |
I'll explain what's being tested in the provided benchmark, describe the options compared, their pros and cons, and other considerations.
What's being tested: The benchmark is testing the performance of three different methods to check if a specific number exists in an array:
indexOf()
includes()
_.includes()
(using Lodash library)Options compared:
indexOf()
: This method searches for the first occurrence of a specified value in the array and returns its index. If the value is not found, it returns -1
.includes()
: This method checks if an element exists in an array, returning true
if found and false
otherwise..includes()
(Lodash): This is a higher-order function that checks if an element exists in an array, similar to the native includes()
method.Pros and Cons of each approach:
indexOf()
:includes()
:indexOf()
for some use cases.indexOf()
for very large arrays..includes()
(Lodash):Other considerations:
includes()
method is tested with both a single value and an empty array, but the latter is not used in any of the test cases.Library usage:
Lodash's .includes()
function is used as a benchmarking tool. Lodash is a popular JavaScript utility library that provides a wide range of functions for common tasks, such as array manipulation, string handling, and more.
Special JS feature or syntax: None mentioned in the provided code or benchmarks.
Alternatives: Other alternatives to these methods could include:
Array.prototype.find()
(ECMAScript 2015+): Returns the first element that satisfies the provided testing function.Array.prototype.findIndex()
(ECMAScript 2015+): Similar to indexOf()
, but returns -1
if not found, instead of throwing an error.Keep in mind that these alternatives may have different performance characteristics and trade-offs compared to the native methods and Lodash's .includes()
function.