#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2009
    Posts
    37
    Rep Power
    16

    Differences in Speed for JavaScript


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

    javascript Code:
     
    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.
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,965
    Rep Power
    9397
    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.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2009
    Posts
    37
    Rep Power
    16
    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.
  6. #4
  7. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,965
    Rep Power
    9397
    Originally Posted by threequestions
    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.

IMN logo majestic logo threadwatch logo seochat tools logo