title: vb.net Regex Improving Performance with compiling and shared variables
body: <p>I am writing some code that uses fixed regexs to search strings and pattern match.</p>
  
  <p>Its simple stuff, but I want to improve regex performance with compiling (its a high traffic website).</p>
  
  <p>I was thinking of compiling the regex and putting it in a Shared (static) variable inside a class.</p>
  
  <p>Something like this:</p>
  
  <pre><code>Namespace Regexs
  
      Public Class UrlNickname
  
          Private Shared rgx As Regex = New Regex("^\/\w{4,20}$", RegexOptions.IgnoreCase Or RegexOptions.CultureInvariant Or RegexOptions.Compiled)
  
          ''' &lt;summary&gt;
          ''' Returns a Nickname string if pattern found in Url, otherwise returns Empty string.
          ''' &lt;/summary&gt;
          ''' &lt;param name="url"&gt;The Url string to search.&lt;/param&gt;
          ''' &lt;returns&gt;&lt;/returns&gt;
          ''' &lt;remarks&gt;&lt;/remarks&gt;
          Public Shared Function ContainsNickname(url As String) As String
              If rgx.IsMatch(url) Then
                  Return url.Substring(1, url.Length - 1)
              End If
              Return String.Empty
          End Function
  
      End Class
  
  End Namespace
  </code></pre>
  
  <p>Then you could use the function like this:</p>
  
  <pre><code>Dim url As String = HttpContext.Current.Request.RawUrl
  
  Dim nickname As String = Regexs.UrlNickname.ContainsNickname(url)
  If Not String.IsNullOrEmpty(nickname) Then
      //nickname pattern match found:
      //do something like RedirectToRoutePermanent
  End If
  </code></pre>
  
  <p>Basically , I store the regex in a Shared (static) variable so that is only compiled once.</p>
  
  <p>The function would then be called to check if a username pattern match was found on a 404 error page.</p>
  
  <p><strong>Whould this be the best approach for improving regex performance?</strong></p>
  
  <p>Note: I am not interested in a solution for 404 error page problems above, its just a simple example.</p>
  
  <hr>
  
  <p>Further advances could then use a Shared generic list of regexs , like so:</p>
  
  <pre><code>Private Shared _rgxList As List(Of Regex)
  
  Public Sub New()
      //get list of regex expressions from database and populate:
      _rgxList.Add(New Regex("blah", RegexOptions.Compiled))
      _rgxList.Add(New Regex("blah2", RegexOptions.Compiled))
  
  Public Shared Function IsMatch(str) as Boolean
      With each reg in _rgxList
          return reg.IsMatch(str)
  </code></pre>
  
  <p>New() would be called on Application.Start event.</p>