2016-11-18 51 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你很稍好一些。