簡體   English   中英

VB.net正則表達式的速度?

[英]Speed of VB.net Regex?

是VB.net中的正則表達式代碼慢嗎?

我接管了一些正在清除大量文本數據的代碼。 代碼運行得很慢,所以我正在尋找一些加快速度的方法。 我發現運行了很多函數,我認為這可能是問題的一部分。

這是清理電話號碼的原始代碼:

        Dim strArray() As Char = strPhoneNum.ToCharArray
        Dim strNewPhone As String = ""
        Dim i As Integer

        For i = 0 To strArray.Length - 1
            If strArray.Length = 11 And strArray(0) = "1" And i = 0 Then
                Continue For
            End If

            If IsNumeric(strArray(i)) Then
                strNewPhone = strNewPhone & strArray(i)
            End If
        Next

        If Len(strNewPhone) = 7 Or Len(strNewPhone) = 10 Then
            Return strNewPhone
        End If

我重寫了代碼,以消除使用正則表達式的數組和循環。

        Dim strNewPhone As String = ""
        strNewPhone = Regex.Replace(strPhoneNum, "\D", "")
        If strNewPhone = "" OrElse strNewPhone.Substring(0, 1) <> "1" Then
            Return strNewPhone
        Else
            strNewPhone = Mid(strNewPhone, 2)
        End If

        If Len(strNewPhone) = 7 Or Len(strNewPhone) = 10 Then
            Return strNewPhone
        End If

運行幾次測試后,新代碼比舊代碼要慢得多。 VB.net中的正則表達式是否運行緩慢,是否添加了其他一些問題,或者原始代碼是否還算不錯?

我使用Visual Studio Profiler進行了一些測試,但沒有得到與您相同的結果。 您的Regex函數存在一個邏輯錯誤,如果數字不是以1開頭,則會導致長度檢查丟失。 我在測試中糾正了這個問題。

  1. 我在測試中意識到,無論第一個還是最后一個函數執行都會受到懲罰。 因此,我獨立執行了每個函數,並在之前運行了啟動函數。
  2. 根據測試,我執行了10000或100000次功能,並使用了不同長度的電話號碼。 每種方法的編號相同。

結果

總的來說,我的方法總是稍快一些。

  1. 我做了一個廉價的計時器測試,原始功能的速度是原來的兩倍。
  2. Profiler顯示原始方法使用的內存比我們的方法多60%。
  3. Profiler顯示原始方法花費的時間是其的八倍。
  4. Profiler顯示原始方法花費了大約40%的處理器周期。

我的結論

在所有測試中,原始方法都慢得多。 如果它在一項測試中表現更好,那么我就能解釋我們的差異。 如果您完全隔離地測試了這些方法,我想您會想到類似的東西。

我最好的猜測是其他因素正在影響您的結果,並且您認為原始方法更好的評估是錯誤的。

您修改的功能

Function GetPhoneNumberRegex(strPhoneNum As String)
    Dim strNewPhone As String = ""
    strNewPhone = Regex.Replace(strPhoneNum, "\D", "")
    If strNewPhone <> "" And strNewPhone.Substring(0, 1) = "1" Then
        strNewPhone = Mid(strNewPhone, 2)
    End If

    If Len(strNewPhone) = 7 Or Len(strNewPhone) = 10 Then
        Return strNewPhone
    End If

    Return ""
End Function

我的功能

Function GetPhoneNumberMine(strPhoneNum As String)
    Dim strNewPhone As String = Regex.Replace(strPhoneNum, "\D", "")
    If (strNewPhone.Length >= 7 And strNewPhone(0) = "1") Then
        strNewPhone = strNewPhone.Remove(0, 1)
    End If

    Return If(strNewPhone.Length = 7 OrElse strNewPhone.Length = 10, strNewPhone, "")
End Function

如果遇到這種情況,重復這樣的事情會使您減速。

 If Len(strNewPhone) = 7 Or Len(strNewPhone) = 10 Then
     Return strNewPhone
 End If

相反,請執行此操作...

     Dim value = Len(strNewPhone)
     If value = 7 OrElse value = 10 Then
         Return strNewPhone
     End If

但是,您仍然應該衡量各個部分(條件/陳述),以確定其中哪一個會拖慢您的速度,但前提是確實如此。

我不知道您是否遇到了真正的問題,但是顯示的代碼可能會變慢,因為每次使用regex都會對其進行重新編譯。

看看這是否更好:

Regex rx = new Regex("\D") ' do this once, use it each time

MSDN上的參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM