Using the compiled RegEx is just like using any other object. Add a reference to it using the Project Properties dialog:
- Right-click the project and select Add Reference...
- Browse to the location of the assembly and select it.
--------
Click Here to display the illustration
Click the Back button on your browser to return
--------
Using a compiled RegEx is the same as any other object.
Dim myCompiledRegex As New myRegExNS.myRegExType
Dim RegExResult As Boolean
RegExResult = myCompiledRegex.IsMatch("String to Match")
But just how much will this speed up your application? Let's find out.
I borrowed the timing code from my StringBuilder article and simply changed the variables a bit and had this running in a few minutes ...
Imports System.Diagnostics
Imports System.Text.RegularExpressions
Public Class CompiledRegEx
Dim InlineTimeSpan As Integer
Dim CompiledTimeSpan As Integer
Dim LoopLimit As Integer
Dim PhoneNum(9999) As String
Dim I As Integer
Private Sub TimeEm_Click( ...
If UseInline.Checked Then UseInlineTest()
If UseCompiled.Checked Then UseCompiledTest()
CalcImprovement()
End Sub
Private Sub UseInlineTest()
Dim myRegexString As New Regex( _
"^1?\s*-?\s*(\d{3}|\(\s*\d{3}\s*\))" & _
"\s*-?\s*\d{3}\s*-?\s*\d{4}$")
Dim RegExResult As Boolean
Dim myStopwatch As Stopwatch = New Stopwatch
Dim myTimeSpan As New TimeSpan
myStopwatch.Reset()
myStopwatch.Start()
For I = 0 To LoopLimit
RegExResult = _
myRegexString.IsMatch(PhoneNum(I).ToString)
Next
myStopwatch.Stop()
myTimeSpan = myStopwatch.Elapsed
InlineTimeSpan = myTimeSpan.Milliseconds
UsingInline.Text = myTimeSpan.ToString
End Sub
Private Sub UseCompiledTest()
Dim myStopwatch As Stopwatch = New Stopwatch
Dim myCompiledRegex As New myRegExNS.myRegExType
Dim RegExResult As Boolean
Dim myTimeSpan As New TimeSpan
myStopwatch.Reset()
myStopwatch.Start()
For I = 0 To LoopLimit
RegExResult = _
myCompiledRegex.IsMatch(PhoneNum(I).ToString)
Next
myStopwatch.Stop()
myTimeSpan = myStopwatch.Elapsed
CompiledTimeSpan = myTimeSpan.Milliseconds
UsingCompiled.Text = myTimeSpan.ToString
End Sub
Private Sub CalcImprovement()
Try
Improvement.Text = _
CStr((InlineTimeSpan / CompiledTimeSpan))
Catch ex As Exception
Improvement.Text = ""
End Try
End Sub
Private Sub CompiledRegEx_Load( ...
Dim PhoneNumSuf As Integer = 0
Dim PhoneNumPre As String = "123-555-"
LoopLimit = CInt(NumberOfIterations.Text) - 1
For I = 0 To LoopLimit
PhoneNum(I) = _
PhoneNumPre & I.ToString.PadLeft(4, "0"c)
Next
End Sub
End Class
The result showed a very significant improvement of about 30 to 50 percent, but frankly, I expected more. On the next page, we get more.
--------
Click Here to display the illustration
Click the Back button on your browser to return
--------

