VB.net Byte Array Search

2.4k views Asked by At

I am in the process of developing a simple virus scanner, and I was searching for speed improvements on the following function:

Public Function FindAInB(ByRef byteArrayA() As Byte, ByRef byteArrayB() As Byte) As Integer
    Dim startmatch As Integer = -1
    Dim offsetA As Integer = 0
    Dim offsetB As Integer = 0

    For offsetB = 0 To byteArrayB.Length - 1
        If byteArrayA(offsetA) = byteArrayB(offsetB) Then
            If startmatch = -1 AndAlso offsetB < byteArrayB.Length - 8 Then
                startmatch = offsetB
            End If
            offsetA += 1
            If offsetA = byteArrayA.Length Then
                Exit For
            End If
        Else
            offsetA = 0
            startmatch = -1
        End If
    Next
    Return startmatch
End Function

I need it to be turbo fast because it's searching for about 7800 byte arrays in a selected file's bytes. Kind of hard to explain but is there an alternative for the code above or a way to speed it up?

Thanks In Advance!

1

There are 1 answers

5
LukeH On

You should check out string search algorithms like Boyer-Moore.

Although you're not actually searching text, you are searching for strings of bytes within a larger string of bytes, so these type of algorithms could help out considerably.