Combine 2 Scripting.Dictionaries or Collections of Key/Item pairs

寵の児 提交于 2019-12-23 03:52:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!