Alex Rivera | Logout

JavaScript: indexOf vs. Match when Searching Strings?

Asked 2011-01-21T09:59:08.843
74

Are there any discernable performance differences between using

str.indexOf("src") 

and

str.match(/src/)

I personally prefer match (and regexp) but colleagues seem to go the other way. We were wondering if it mattered ...?

EDIT:

I should have said at the outset that this is for functions that will be doing partial plain-string matching (to pick up identifiers in class attributes for JQuery) rather than full regexp searches with wildcards etc.

class='redBorder DisablesGuiClass-2345-2d73-83hf-8293' 

So it's the difference between:

string.indexOf('DisablesGuiClass-');

and

string.match(/DisablesGuiClass-/)
Edit
Report

2 Answers

63

RegExp is indeed slower than indexOf (you can see it here), though normally this shouldn't be an issue. With RegExp, you also have to make sure the string is properly escaped, which is an extra thing to think about.

Both of those issues aside, if two tools do exactly what you need them to, why not choose the simpler one?

answered 2011-01-21T10:06:58.493
4

Performance wise indexOf will at the very least be slightly faster than match. It all comes down to the specific implementation. When deciding which to use ask yourself the following question:

Will an integer index suffice or do I need the functionality of a RegExp match result?

answered 2011-01-21T10:05:21.113

Your Answer