Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array indexOf() vs includes() perfomance depending on browser and needle position

Tags:

javascript

Is there any advantage to Array.prototype.includes() over Array.prototype.indexOf() depending on browsers (Chrome, Firefox) and needle item position (at the begging, middle, ending of the array)?

Array.prototype.includes vs. Array.prototype.indexOf There is no browser specific information, there is no position in the array specific information, and I don't ask about NaN value.

like image 491
Luther Lisle Avatar asked Dec 05 '17 18:12

Luther Lisle


People also ask

Which is faster includes or indexOf?

indexOf will accept a regular expression but always return -1, which isn't too helpful. So while includes will be a tiny, tiny amount slower because it has to check if you passed it a regex, in reality this will make no difference to how fast your code runs.

Should I use indexOf or includes?

indexOf() returns the index if found, -1 if not. If you are searching for NaN (not a number) in an array, use . includes().

What is the time complexity of indexOf?

indexOf() – also runs in linear time. It iterates through the internal array and checks each element one by one, so the time complexity for this operation always requires O(n) time.

What is the difference between the array object's indexOf and lastIndexOf methods?

Basically indexOf & lastIndexOf are native javascript functions. Both functions can be applied on Strings as well as Arrays . The indexOf return the very first index where the element matched. On the other hand lastIndexOf returns the last index where the element matched.


2 Answers

I made a test using array with 10 000 numeric values, here is results:

Chrome:

  • beginning
    • includes (22,043,904 ops/sec)
    • indexOf (136,512,737 ops/sec)
  • middle
    • includes (8,361 ops/sec)
    • indexOf (31,296 ops/sec)
  • ending
    • includes (4,018 ops/sec)
    • indexOf (95,221 ops/sec)

Firefox:

  • beginning
    • includes (34,087,623 ops/sec)
    • indexOf (33,196,839 ops/sec)
  • middle
    • includes (84,880 ops/sec)
    • indexOf (86,612 ops/sec)
  • ending
    • includes (25,253 ops/sec)
    • indexOf (14,994 ops/sec)

So, indexOf() in Chrome works much faster than includes() in all positions.

In Firefox both indexOf() and includes() works almost similar.

like image 95
Carl Schultz Avatar answered Sep 29 '22 11:09

Carl Schultz


If you wonder about performances, here is a JSperf test that tend to show that more the time pass, more includes() will be faster than indexOf.

JSperf

IMHO, i also prefer to write if (arr.includes(el)) {} since it is clearer and more maintainable than if (arr.indexOf(el) !== -1) {}

like image 21
Johnny Gibby Avatar answered Sep 29 '22 13:09

Johnny Gibby