Readability aside, are there any discernable differences (performance perhaps) 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-/)
IndexOf is only useful for checking the existence of an exact substring, but Regex is much more powerful and allows you to do so much more.
For just finding a keyword the IndexOf method is faster than using a regular expression. Regular expressions are powerful, but their power lies in flexibility, not raw speed. They don't beat string methods at simple string operations.
The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.
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?
Your comparison may not be entirely fair. indexOf
is used with plain strings and is therefore very fast; match
takes a regular expression - of course it may be slower in comparison, but if you want to do a regex match, you won't get far with indexOf
. On the other hand, regular expression engines can be optimized, and have been improving in performance in the last years.
In your case, where you're looking for a verbatim string, indexOf
should be sufficient. There is still one application for regexes, though: If you need to match entire words and want to avoid matching substrings, then regular expressions give you "word boundary anchors". For example:
indexOf('bar')
will find bar
three times in bar, fubar, barmy
, whereas
match(/\bbar\b/)
will only match bar
when it is not part of a longer word.
As you can see in the comments, some comparisons have been done that show that a regex may be faster than indexOf
- if it's performance-critical, you may need to profile your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With