Search code examples
vb6

VB6: How to search an array fast?


say, i have a string array of 50000 elements. Searching the array using For Next is so slow for such a huge array. Is there any fast way to search?

Note: Using join & instr we can search for a string in an array, but this method is no good as i can not find out the element number

Note: the array is unsorted. And i'm looking for substrings


Solution

  • This is an expansion of your idea to use Join and InStr:

    Sub TestArraySearch()
    Dim A(4) As String
        A(0) = "First"
        A(1) = "Second"
        A(2) = "Third"
        A(3) = "Fourth"
        A(4) = "Fifth"
        Debug.Print FastArraySearch(A, "Fi")
        Debug.Print FastArraySearch(A, "o")
        Debug.Print FastArraySearch(A, "hird")
        Debug.Print FastArraySearch(A, "Fou")
        Debug.Print FastArraySearch(A, "ndTh")
        Debug.Print FastArraySearch(A, "fth")
    End Sub
    
    Function FastArraySearch(SearchArray As Variant,SearchPhrase As String) As String
    Dim Pos As Long, i As Long, NumCharsProcessed As Long, Txt As String
        Pos = InStr(Join(SearchArray, "§"), SearchPhrase)
        If Pos > 0 Then
            For i = LBound(SearchArray) To UBound(SearchArray)
                NumCharsProcessed = NumCharsProcessed + Len(SearchArray(i)) + 1
                If NumCharsProcessed >= Pos Then
                    FastArraySearch = SearchArray(i)
                    Exit Function
                End If
            Next i
        End If
    End Function
    

    I did not benchmark it, but it should be quicker than doing a separate search each time through the loop. It searches once, then just adds up the string lengths until it gets to where the match was. Because the length of the string is stored before any of the characters in the string, the Len function is highly optimized.

    If this performance is still unacceptable I think you will need to find a different data structure than an array (eg, a disconnected recordset, as @Remou suggested).