I have a large complex VBA script I wrote for work. I am in the process of cleaning it up and noticed I could define my array in what seams like a more dynamic way than I was doing it.
Originally I was defining my Array As String like this:
Dim header_arr(6) As String
Dim header_arr_2(4) As String
header_arr(0) = "esn"
header_arr(1) = "vin"
header_arr(2) = "last gps update time"
header_arr(3) = "status"
header_arr(4) = "account name"
header_arr(5) = "vehicle #"
header_arr_2(0) = "esn"
header_arr_2(1) = "vin"
header_arr_2(2) = "last gps update time"
header_arr_2(3) = "status"
header_arr_2(4) = "vehicle #"
Then I was playing around with how to assign an Array and managed to reduce it to this:
Dim header_arr
header_arr = Array("esn", "vin", "last gps update time", "status", "account name", "vehicle #")
' Function call with this first Array
header_arr = Array("esn", "vin", "last gps update time", "status", "vehicle #")
' Function call with this second Array
My Question is this:
I know that for this simple portion of the script the CPU cost is not relaven but for much larger Array's what method of writing an Array is the lowest CPU cost if any difference at all?
I have not been able to find much on performance differences between the different methods of defining an Array.
header_arr(6) As Stringis an array of strings. The result returned byArray()is aVariantcontaining an array ofVariants. Obviously the latter has more overhead.Dim header_arr As Variantis exactly the same asDim header_arr. You can't assign a Variant/Array to a strictly typed variable, you have to do it line by line. You can, however, pass a strictly typed array to a function without copying the array, provided the function parameter is declaredByRef ... As Variant, and same function would be able to accept a Variant/Array. UsingByVal ... As Variantwould result in copying the array upon call.Array(...), what's that about then?Recordsetmight be a much better idea. Or the values might be on a worksheet, in which case you get them into a 2D variant array pretty much instantly with a single line of code. Depends what you need =)