Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I understand the advantage of using RegexOptions.Compiled - it improves upon the execution time of app by having the regular expression in compiled form instead of interpreting it at run-time. Although using this is not recommended for application which are already slow at start-up time.

But if my application can bear any slight increase in start-up time -
what are the other scenarios in which I should NOT use RegexOptions.Compiled?

Just as a note I am calling this method several times -

private static string GetName(string objString)
{
    return Regex.Replace(objString, "[^a-zA-Z&-]+", "");
}

So, this method is called with different values for 'objString' (although values for objString may repeat as well).

Do you think it's good/not good to use RegexOptions.Compiled here? Any web link would be really helpful.
Thank you!


EDIT

I tested my web app with both

  • RegexOptions.Compiled, and
  • Instantiate Regex as class variable

But couldn't find any big difference in time taken by my web application - Only thing I noticed in both scenarios is that first time when the application loads it's taking double of the time taken compared to that in successive page loads and that is irrespective of whether I use RegexOptions.Compiled or not.

Any comments for --
why my web application takes longer for the Regex to process for first time and time taken is reduced to almost half or less in subsequent loads - Is there any inbuilt caching or some other .net feature is helping here. P.S. This thing is same if I use RegexOptions.Compiled or not.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
234 views
Welcome To Ask or Share your Answers For Others

1 Answer

For any specific performance question like this, the best way to find out which way is faster is to test both and see.

In general, compiling a regex is unlikely to have much benefit unless you're using the regex a lot, or on very large strings. (Or both.) I think it's more of an optimization to try after you've determined that you have a performance problem and you think this might help, than one to try randomly.

For some general discussion on the drawbacks of RegexOptions.Compiled, see this blog post by Jeff Atwood; it's very old (from the days of .NET Framework 1.1), but from what I understand, none of the major relevant facts have changed since it was written.



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...