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

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.


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) {}

Tags:

Javascript