在 64 位 Excel 中使用字典时内存未释放

问题描述 投票:0回答:1

当我将数据存储在字典中时,超出范围或设置为 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 位

excel vba vba7
1个回答
0
投票

我最近遇到了一些与字典无关的内存问题。 我还必须有时设置

Application.ScreenUpdating = True
(从我记事起,这就是自动完成的)。 希望很快就会有补丁发布。

Version: 16.0
Build: 18025
Architecture: 64-bit

遇到奇怪的行为时,请考虑使用MZ Tools清理项目功能。

MZ工具文档

Clean Project Document

© www.soinside.com 2019 - 2024. All rights reserved.