Add item to array in VBScript
Arrays are not very dynamic in VBScript. You'll have to use the ReDim Preserve statement to grow the existing array so it can accommodate an extra item:
ReDim Preserve yourArray(UBound(yourArray) + 1)yourArray(UBound(yourArray)) = "Watermelons"
There are a few ways, not including a custom COM or ActiveX object
- ReDim Preserve
- Dictionary object, which can have string keys and search for them
- ArrayList .Net Framework Class, which has many methods including:sort (forward, reverse, custom), insert, remove,binarysearch, equals, toArray, and toString
With the code below, I found Redim Preserve is fastest below 54000, Dictionary is fastest from 54000 to 690000, and Array List is fastest above 690000. I tend to use ArrayList for pushing because of the sorting and array conversion.
user326639 provided FastArray, which is pretty much the fastest.
Dictionaries are useful for searching for the value and returning the index (i.e. field names), or for grouping and aggregation (histograms, group and add, group and concatenate strings, group and push sub-arrays). When grouping on keys, set CompareMode for case in/sensitivity, and check the "exists" property before "add"-ing.
Redim wouldn't save much time for one array, but it's useful for a dictionary of arrays.
'pushtest.vbsimax = 10000value = "Testvalue"s = imax & " of """ & value & """" t0 = timer 'ArrayList MethodSet o = CreateObject("System.Collections.ArrayList")For i = 0 To imax o.Add valueNexts = s & "[AList " & FormatNumber(timer - t0, 3, -1) & "]"Set o = Nothingt0 = timer 'ReDim Preserve Methoda = array()For i = 0 To imax ReDim Preserve a(UBound(a) + 1) a(UBound(a)) = valueNexts = s & "[ReDim " & FormatNumber(timer - t0, 3, -1) & "]"Set a = Nothingt0 = timer 'Dictionary MethodSet o = CreateObject("Scripting.Dictionary")For i = 0 To imax o.Add i, valueNexts = s & "[Dictionary " & FormatNumber(timer - t0, 3, -1) & "]"Set o = Nothingt0 = timer 'Standard arrayRedim a(imax)For i = 0 To imax a(i) = valueNexts = s & "[Array " & FormatNumber(timer - t0, 3, -1) & "]" & vbCRLFSet a = Nothingt0 = timer 'Fast arraya = array()For i = 0 To imax ub = UBound(a) If i>ub Then ReDim Preserve a(Int((ub+10)*1.1)) a(i) = valueNextReDim Preserve a(i-1)s = s & "[FastArr " & FormatNumber(timer - t0, 3, -1) & "]"Set a = NothingMsgBox s' 10000 of "Testvalue" [ArrayList 0.156][Redim 0.016][Dictionary 0.031][Array 0.016][FastArr 0.016]' 54000 of "Testvalue" [ArrayList 0.734][Redim 0.672][Dictionary 0.203][Array 0.063][FastArr 0.109]' 240000 of "Testvalue" [ArrayList 3.172][Redim 5.891][Dictionary 1.453][Array 0.203][FastArr 0.484]' 690000 of "Testvalue" [ArrayList 9.078][Redim 44.785][Dictionary 8.750][Array 0.609][FastArr 1.406]'1000000 of "Testvalue" [ArrayList 13.191][Redim 92.863][Dictionary 18.047][Array 0.859][FastArr 2.031]