Recently we encountered a huge performance issue in our HttpModule or Url Rewriter module. After a lot of tense and investigation, the issue is locked down at the way of using Regular Expression. In the HttpModule, we are using Regex to match certain patterns of urls and redirect or rewrite the url based on the patterns. Apparently we have so many urls to check against by using 40 patterns. Unfortunately, we used the regular expression as below...
//for loop
Regex regex = new Regex(strPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
if (regex.IsMatch([Current Url])){
// Redirect or Rewrite
}
You may already notice that the creation of the Regex instance is within the loop and has Compiled option, which suppose to optimize the expresson, but since it is with HttpModule, every request is going through this logic, the initialization of the regular expression instance is taking all the CUP resource.
The resolution to this is simple if we know the cause.
1, Move the initialization of Regex objects outside the for loop
2, Use singleton pattern to return only one set of these Regex objects
3, Inside the for loop, only use IsMatch method of those Regex objects.
This reduced our CPU usage dramatically from 90% to <10%