简体   繁体   中英

Excel VBA - Iterating through 2D arrays that are stored in a dictionary (performance)

I have a piece of code that is doing some operations in 2D arrays that are themself stored in a dictionary.

My goal is to loop through the dictionary, and iterating in every item (a 2D array) to do some operation. Every row of these 2D arrays are then stored in a final 2D array.

The code works pretty fine but is very slow, knowing that the 2D arrays aren't big at all (3000 rows tops & 10 columns tops).

Private Function Process_Data(ByVal var1 As Variant, ByVal var2 As Variant, ByVal var3 As Variant, ByVal var4 As Variant, ByVal var5 As Variant)

    Dim res As Variant
    Dim size_dim1 As Long: Dim size_dim2 As Long
    Dim dic As New Dictionary
    Dim i As Long: Dim j As Long: Dim k As Long
    Dim key As Variant

    'Fill dic with parameters
    dic.Add 1, var1
    dic.Add 2, var2
    dic.Add 3, var3
    dic.Add 4, var4
    dic.Add 5, var5

    'Dim final array
    size_dim1 = UBound(var1, 1) + UBound(var2, 1) + UBound(var3, 1) + UBound(var4, 1) + UBound(var5, 1)
    size_dim2 = 8   'col H
    ReDim res(1 To size_dim1, 1 To size_dim2)
    j = 1

    'Various elements in the final 2D array (res)
    For Each key In dic.Keys
        For i = LBound(dic(key), 1) To UBound(dic(key), 1)
            res(j, 1) = dic(key)(i, 1)     'Whatever happens here
            res(j, 2) = dic(key)(i, 2)
            res(j, 3) = dic(key)(i, 3)
            res(j, 4) = dic(key)(i, 4)
            res(j, 5) = dic(key)(i, 5)
            res(j, 6) = ""
            res(j, 7) = ""
            res(j, 8) = ""
            j = j + 1
        Next i
    Next key

    Process_Data = res
End Function

Do you have any suggestions to improve my code here?

Thanks a lot for your time! Chris

You do not leverage any advantage of using dictionary (at least as is shown in the code) but you suffer the administrative overhead of dictionary 5*size_dim1 times. I would refactor your code this way:

...
j = 1

j=Process_Data_Add_Buf (res, var1, j)
j=Process_Data_Add_Buf (res, var2, j)
j=Process_Data_Add_Buf (res, var3, j)
j=Process_Data_Add_Buf (res, var4, j)
j=Process_Data_Add_Buf (res, var5, j)

Process_Data = res
End Sub

Private Function Process_Data_Add_Buf (byref OutBuf() as Variant, Byref InBuf() as variant, iRow as Long) as Long
Dim i as long
For i = LBound(InBuf, 1) To UBound(InBuf, 1)
        OutBuf(iRow, 1) = InBuf(i, 1)     'Whatever happens here
        ...
        iRow = iRow + 1
Next i
Process_Data_Add_Buf = iRow
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM