RegexRouteConstraint should use Compiled Regex
See original GitHub issueToday, when using a regex route constraint, we create a new Regex:
This should use the RegexOptions.Compiled as well. That way we aren’t interpreting these regular expressions every time the route is inspected.
Our docs even say this should be using Compiled:
The ASP.NET Core framework adds RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.CultureInvariant to the regular expression constructor. See RegexOptions for a description of these members.
Issue Analytics
- State:
- Created 8 months ago
- Comments:20 (20 by maintainers)
Top Results From Across the Web
Is it bad to use regex based route constraints?
I have the following route that will be hit extensively on my ASP.NET MVC website: routes.MapRoute( null, "products/{ProductID}/{SeoName}", new ...
Read more >Using source-generated regex in ASP.NET Core route ...
In this post, I describe how to use source-generated regex in ASP.NET Core routing to improve startup time.
Read more >Best Practices for Regular Expressions in .NET
You should use compiled regular expressions when you call regular expression methods with a specific regular expression relatively ...
Read more >Compilation and Reuse in Regular Expressions
You can compile all of your expressions into a reusable DLL by using the CompileToAssembly method. This avoids the need to compile at...
Read more >To Compile or Not To Compile
I noticed that I had sort of mindlessly added RegexOptions.Compiled all over the place. It says "compiled" so it must be faster, right?...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

@surayya-MS From the discussion in our call, here is an example of configuring the
regexroute to go back to the old behavior:This is the escape hatch we can recommend to customers if, even after improvements, their app has problems with compiled regexes.
Test app with 30,000 regex routes:
Time to first request:
App memory usage:
I think we should:
Regexconstruction lazy until needed.That will bring first request and memory usage down to “no regex” results for most apps. We get our cake and eat it too: improved startup performance and regex per-request performance.
There still might be some edge-case apps out there that perform worst. They have lots of unique regex routes, and they all get visited, and memory usage is a problem. Routing is configurable so we can advise them to configure the regex constraint with an implementation that doesn’t call
RegexOptions.Compiled.