加速MS ACCESS VBA脚本迭代字符串中的字节

时间:2016-11-18 11:31:23

标签: ms-access access-vba

我需要一个非常简单的哈希函数,基于excel的一些实验,只需要一个字节值的总和就可以了:

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

在查询产生的所有记录(大约100)上执行了很多次:

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迭代字符串的版本甚至更慢,但现在我没有想法如何改进它。

有没有办法加快速度?

编辑:问题不在哈希函数中,而是在查询中。

2 个答案:

答案 0 :(得分:3)

使用常量字符串的测试代码显示函数本身非常快。 10,000个字符串的调用。 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

答案 1 :(得分: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你会非常轻微更好。