Helpful Information
 
 
Category: Regex Programming
Differences in Speed for JavaScript

I have three ways to check for a pattern within a string.


string.match(pattern) // just checks for match
pattern.exec(string) // can return array with backreferences, etc, then check for match within reference
pattern.test(string) // just checks for match


Which is faster, if even applicable? I know this can also depend on the browser, but inherently, which is faster?

My background is mainly with PHP, where dozens of sites online have written articles testing the merits and speeds of different regular expression and string matching functions, and compare. I couldn't find the same kind of articles for JavaScript.

It probably depends on the implementation. Not just speed but what's better.
For example, regexp.exec could simply call off string.match or regexp.text and return whether there was a match to begin with. In which case it's slower than the other two.
Or the implementation could be nice and actually do the work, where it'd probably be faster than the others.

If you're using this for speed then you're doing it wrong: (a) it's JavaScript, and (b) you're using regular expressions.

Just do whatever makes most sense to you.

Thanks for the input requinix. I decided on exec because I needed to have some values returned from the backreferences.

What would you recommend for speed? I take it that JavaScript is not up there.

What would you recommend for speed? I take it that JavaScript is not up there.
Well it really depends on what you're trying to do. For the most part using JavaScript will be fine, it's not like it takes tenths of a second to do something. But the more complicated the expression and the larger the input the slower it will run.

Don't worry about it unless you start noticing (or people start complaining about) lag.










privacy (GDPR)