2016-11-18 45 views
1

我需要根據一些實驗用Excel中的一個非常簡單的哈希函數,只是一個字節值的總和應該這樣做:加快MS ACCESS VBA腳本遍歷字節字符串

Function HashPart(strVal As String) As Long 
    ' work with byte representation for speed 
    Dim b() As Byte 
    b = strVal 

    Dim result As Long 
    result = 0 
    For i = 0 To UBound(b) 
     result = result + b(i) 
    Next 
    Quersumme = result 
End Function 

這是做了很多time over all query(about 100)from a query:

Set rs = db.OpenRecordset(strSQL) 

' Loop through records 
Do While Not rs.EOF 
    resultHash = resultHash + HashPart(rs(0)) 
    resultLen = resultLen + Len(rs(0)) 
    rs.MoveNext 
Loop 
rs.Close 
MyHash = Str(resultLen) & "-" & Str(resultHash) 

這個效果很好,但速度很慢。我以前的版本使用Mid進行字符串迭代的速度更慢,但現在我不知道如何改進這一點。

有沒有辦法加快速度?


編輯:問題不在散列函數中,而是在查詢中。

+0

我看不出你量化'HashPart ='的位置。 – user3819867

+0

@ user3819867修好了,謝謝! – Beginner

+1

您的琴絃需要多長時間(平均)?「非常慢」的速度有多慢?如果我用110個字符的常量字符串運行10000次,則需要0.04秒。所以很可能你的查詢很慢,而不是函數。 – Andre

回答

3

帶有常量字符串的測試代碼顯示函數本身非常快。 10,000個調用字符串的ca. 110個字符只需要0.04秒。

結論:性能問題出現在查詢中,而不是哈希函數。

Function HashPart(strVal As String) As Long 

    ' work with byte representation for speed 
    Dim b() As Byte 
    Dim result As Long 
    Dim i As Long 

    b = strVal 
    result = 0 

    For i = 0 To UBound(b) 
     result = result + b(i) 
    Next 

    HashPart = result 

End Function 

Sub TestHashPart() 

    Const NumRounds = 10000 

    Dim i As Long 
    Dim res As Long 
    Dim SumRes As Double ' avoid limitation of Long (2^31) 
    Dim S As String 
    Dim t1 As Single 

    t1 = Timer 
    For i = 1 To NumRounds 
     ' constant string with tiny variations 
     S = "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ " & CStr(i^2) 
     res = HashPart(S) 
     ' This would slow down the process dramatically. DO NOT activate for NumRounds > 1000 ! 
     ' Debug.Print i, res, Len(S), S 
     SumRes = SumRes + res 
    Next i 

    Debug.Print SumRes, Timer - t1 & " seconds" 

End Sub 
+0

謝謝!在向正確的方向搜索後,我找到了一種加快速度的方法。 – Beginner

1
Function HashPart(strVal As String) As Long 
    ' work with byte representation for speed 
    Dim b() As Byte 
    b = strVal 
    For i = 0 To UBound(b) 
     HashPart = HashPart + b(i) 
    Next 
End Function 

沒有太多改善,我認爲,如果你不把額外的變量在那裏,並沒有設置數量爲0,默認值爲0你很稍好一些。