JavaScript indexOf vs includes performance

This is a short response I wrote to a question on /r/javascript. The user who asked it was curious whether there would be any performance difference between using a JavaScript string’s indexOf vs includes performance when trying to find a substring within a larger string. 

Let’s take a look at the ECMAScript specification to see what it says.  

In the case of indexOf vs includes, you’ll find them right next to each other here in the ECMAScript spec. The only difference is that includes checks if you’ve passed it a regular expression instead of a string, and throws an exception if you have. 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. You should use indexOf if you care about where the substring is in the original string. If you don’t care, just call includes because it makes the intent of your code more clear.

You should also consider that indexOf won’t find the location of NaN values in an Array. For cases where you really need to find the first location of something that indexOf can’t find, and you don’t want to loop the array through yourself, then Array.prototype.findIndex is your friend. You can pass it a function that returns true when it sees the value you’re looking for. So [1, 2, 3, NaN, 4].findIndex(Number.isNaN) would return 3.

The verdict: in most cases, in terms of JavaScript indexOf vs include performance it doesn’t matter much whether you use index vs includes. You should pick the one that’s the clearest fit for the problem you’re trying to solve.

If you liked this, you might like these other articles I’ve written:
Using Web Components with React in 2019
An Angular Roadmap – The Past, Present, and Future of Angular
How do JavaScript Arrays Work Under the Hood?

One Reply to “JavaScript indexOf vs includes performance”

  1. […] to this article on the subject there are no noticeable difference although includes may be a very little bit […]

Leave a Reply

Your email address will not be published. Required fields are marked *

© 2024 Ryan Peden . Powered by WordPress. Theme by Viva Themes.