Things to consider when using compiled Regex in extensions

Things to consider when using compiled Regex in extensions

  
When you're creating extensions that use .Net Regular Expressions, there are some things that can drastically change the application's performance that you should keep in mind.
  • If you'll be always using the same expressions, avoid using Regex.* static methods (such as Regex.Replace). Instead create a new instance of the Regex class (Regex r = new Regex("expression");) and reuse that object. You can set the object as a static variable to share it across requests as it is perfectly thread-safe.
  • If you'll use your regular expression only once in a lifetime, there's no practical gain in setting RegexOptions.Compiled. There may actually be a performance penalty as most times the application will spend more time compiling the regular expression than benefiting from such an optimization.
  • When considering the above points, remember that having a single regex call in a procedure doesn't mean it's invoked once in a lifetime, as that procedure could be invoked countless times for a single screen preparation.


These points are more notorious in .Net 2.0 (OutSystems Platform 4.1) than they were in .Net 1.1 (OutSystems Platform 4.0). In .Net 2.0 the misuse of regex objects through ignoring the stated points can make a regex-intensive application about 3000 times slower. That's like going from 0.046 seconds to 2:41.