当我将数据存储在字典中时,超出范围或设置为 Nothing 后内存不会释放。我必须显式使用RemoveAll方法来释放内存。
此问题仅出现在 Office 365 64 位版本中,而不会出现在之前使用的 32 位版本中。
例如:
Public Sub testDict()
Dim dict As Dictionary
Dim i As Long
Set dict = New Dictionary
For i = 1 To 100000
dict.Add i, Format(i, "0000000000")
Next
dict.RemoveAll
Set dict = Nothing
End Sub
如果本例中没有使用dict.RemoveAll,则Sub完成后内存不会被释放。该 Sub 的每次新执行都将使用新内存。
使用RemoveAll方法释放内存对于嵌套字典不起作用。
例如:
Public Sub testNestedDict()
Dim i As Long
Dim j As Long
Dim k As Long
Dim dict As Dictionary
Set dict = New Dictionary
For i = 1 To 10
dict.Add i, New Dictionary
For j = 1 To 10
dict(i).Add j, New Dictionary
For k = 1 To 10
dict(i)(j).Add k, New Dictionary
Next
Next
Next
dict.RemoveAll
Set dict = Nothing
End Sub
在这种情况下,每次执行都会消耗大约 10MB 的内存。 我什至尝试构建一个递归删除字典的函数。
Public Sub testNestedDict()
Dim i As Long
Dim j As Long
Dim k As Long
Dim dict As Dictionary
Set dict = New Dictionary
For i = 1 To 10
dict.Add i, New Dictionary
For j = 1 To 10
dict(i).Add j, New Dictionary
For k = 1 To 10
dict(i)(j).Add k, New Dictionary
Next
Next
Next
dictErase dict
End Sub
Public Function dictErase(ByRef dict As Dictionary)
Dim key As Variant
If dict Is Nothing Then
Exit Function
End If
For Each key In dict.Keys()
If TypeOf dict(key) Is Dictionary Then
dictErase dict(key)
End If
Next
dict.RemoveAll
Set dict = Nothing
End Function
这也行不通。
看来这个问题不仅仅局限于词典。在 64 位版本的 VBA 中,超出范围变量的内存似乎未正确释放,或者至少与 32 位版本相比表现不同。
不适用于 Microsoft® Excel® for Microsoft 365 MSO(版本 2408 Build 16.0.17928.20114)64 位
工作版本:Microsoft® Excel® 2019 MSO (16.0.10413.20020) 32 位