When not to use RegexOptions.Compiled

前端 未结 4 1101
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 06:10

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 interpre

4条回答
  •  醉梦人生
    2020-12-13 06:28

    Two things to think about are that RegexOptions.Compiled takes up CPU time and memory.

    With that in mind, there's basically just one instance when you should not use RegexOptions.Compiled :

    • Your regular expression only runs a handful of times and the net speedup at runtime doesn't justify the cost of compilation.

    There are too many variables to predict and draw a line in the sand, so to speak. It'd really require testing to determine the optimal approach. Or, if you don't feel like testing, then don't use Compiled until you do.

    Now, if you do choose RegexOptions.Compiled it's important that you're not wasteful with it.

    Often the best way to go about it is to define your object as a static variable that can be reused over and over. For example...

    public static Regex NameRegex = new Regex(@"[^a-zA-Z&-]+", RegexOptions.Compiled);
    

    The one problem with this approach is that if you're declaring this globally, then it may be a waste if your application doesn't always use it, or doesn't use it upon startup. So a slightly different approach would be to use lazy loading as I describe in the article I wrote yesterday.

    So in this case it'd be something like this...

    public static Lazy NameRegex = 
        new Lazy(() => new Regex("[^a-zA-Z&-]+", RegexOptions.Compiled));
    

    Then you simply reference NameRegex.Value whenever you want to use this regular expression and it's only instantiated when it's first accessed.


    RegexOptions.Compiled in the Real World

    On a couple of my sites, I'm using Regex routes for ASP.NET MVC. And this scenario is a perfect use for RegexOptions.Compiled. The routes are defined when the web application starts up, and are then reused for all subsequent requests as long as the application keeps running. So these regular expressions are instantiated and compiled once and reused millions of times.

提交回复
热议问题