问题
Is there a more efficient way to combine 2 dictionaries in VBScript / VBA? I wrote the function below, but I'm worried about the performance impact:
Function MergeDicts(Dct1, Dct2)
'Merge 2 dictionaries. The second dictionary will override the first if they have the same key
Dim Res, Key
Set Res = CreateObject("Scripting.Dictionary")
For Each Key In Dct1.Keys()
Res.Item(Key) = Dct1(Key)
Next
For Each Key In Dct2.Keys()
Res.Item(Key) = Dct2(Key)
Next
Set MergeDicts = Res
End Function
回答1:
If you'd like to improve performance, don't use late binding :
Dim Res
Set Res = CreateObject("Scripting.Dictionary")
use early binding instead.
Add reference to Microsotf Scripting Runtime library (go to TOOLS->REFERENCES)
and then use:
Dim Res as New Dictionary
Your algorithm is fine. Merging two dictionaries (each contains 10000 key/value pairs) takes on my machine 0.046875 seconds for early binding and 0.069841 for late binding.
回答2:
If you really need the merged dictionary, you can't avoid the CreateObject, the two loops, and the assignments. You could try whether counted loops - For i = 0 To UBound(dictX.Keys()) - is faster. A slight change of specs - keep value of first dictionary - would allow an experiment wrt. checking Res.Exists(Dct2-Key) to avoid 'unnecessary' assignments.
Perhaps an inlining
If Dct1.Exists(key) Then
...
Else
If Dct2.Exists(key) Then
...
is more efficient, but whether is's a good idea obviously depends on your script in toto.
来源:https://stackoverflow.com/questions/21903530/combine-2-scripting-dictionaries-or-collections-of-key-item-pairs