我在这里找到的主题回答了我正在寻找的一半: Does Scripting.Dictionary's RemoveAll() method release all of its elements first?
在我的情况下,值是Dictionary的实例,所以我有嵌套的Dictionary对象层次结构。
我的问题是我是否需要在每个子词典上调用RemoveAll?
' just for illustration
Dim d As Dictionary
Set d = New Dictionary
Set d("a") = New Dictionary
Set d("b") = New Dictionary
' Are the next section of code necessary?
' -------------------- section start
Dim key As Variant
For Each key In d
d.Item(key).RemoveAll
Next
' -------------------- section end
d.RemoveAll
Set d = Nothing
答案 0 :(得分:0)
考虑这段代码
Option Explicit
Private m_cCache As Collection
Private Sub Form_Load()
' just for illustration
Dim d As Dictionary
Set d = New Dictionary
Set d("a") = New Dictionary
Set d("b") = New Dictionary
d("b").Add "c", 123
SomeMethod d
' Are the next section of code necessary?
' -------------------- section start
Dim key As Variant
For Each key In d
d.Item(key).RemoveAll
Next
' -------------------- section end
d.RemoveAll '--- d("b") survives
Set d = Nothing '--- d survives
Debug.Print "main="; m_cCache("main").Count, "child="; m_cCache("child").Count
End Sub
Private Sub SomeMethod(d As Dictionary)
Set m_cCache = New Collection
m_cCache.Add d, "main"
m_cCache.Add d("b"), "child"
End Sub
如果没有清理,d(“b”)部分几乎不受影响 - 儿童既不会被移除,也不会被终止。
答案 1 :(得分:0)
好的,我想我可以通过下一次测试来回答自己。
Sub Main()
Dim d As Dictionary
Dim i, j As Integer
Dim sDummy As String * 10000
For i = 1 To 1000
Set d = New Dictionary ' root dict.
Set d("a") = New Dictionary ' child dict.
For j = 1 To 1000
d("a").Add j, sDummy
Next j
'd("a").RemoveAll
d.RemoveAll
Set d = Nothing
Next i
End Sub
我评论d("a").RemoveAll
(我的孩子字典),没有任何内存泄漏。这意味着在根(RemoveAll
)上调用d
就足够了,这就是我需要知道的全部内容。
答案 2 :(得分:0)
在VB6中,所有对象(通过COM)都需要参考计数,因此,除非有一个循环,否则您不需要手动处理。