VBA:将对象添加到集合会增加内存使用量
我不喜欢在这样的论坛上提问,因为我相信每一个问题都在我面前提出,所以我只是使用search。 但现在我觉得自己有点愚蠢,因为这是我第一次没有find答案。
我有一个基于一段代码的简单问题:
Dim demo_1, demo_2 As Variant 'declare the variables Dim DataCollection As Collection 'declare the collection Set DataCollection = New Collection 'define the collection demo_1 = import_demo(1, nb_var) 'load first dataset (+250 mb of memory) demo_2 = import_demo(2, nb_var) 'load second dataset (+250 mb of memory)
所以总的来说,我的程序使用了500MB的内存。 现在我想填充我的集合引用这个对象:
DataCollection.Add demo_1 'adding reference to a collection (+250 mb of memory Why??) DataCollection.Add demo_2 'adding reference to a collection (+250 mb of memory Why??)
所以我重复一下我的问题:“为什么? 抱歉。
如果向集合中添加对象,会增加VBA中的内存使用量,因为我显然不克隆?
它看起来像你的import_demo(1, nb_var)
函数返回一个数组。 将数组添加到集合中会添加数组的副本 。 如果你的函数返回一个250MB的数组,那么该数组的每一个副本将会增加另一个250MB。
看到这个简化的例子:
Sub test() Dim coll As Collection Set coll = New Collection Dim arr As Variant arr = Array(1, 2, 3) 'Add the array to the collection (makes a copy) coll.Add arr 'Change the ooriginal array arr(0) = 4 Debug.Print coll(1)(0), arr(0) 'Prints 1,4 End Sub
但是,这听起来像你想参考工作。 为此,您的函数将需要返回一个对象/类实例,然后将其添加到集合中。
如果你的函数打算返回一个Range
,你赋值给demo_1 = import_demo(1, nb_var)
会隐式地调用Range.[_Default]
属性(相当于Range.Value
)。 为了返回Range
对象 ,你需要使用Set
关键字: Set demo_1 = import_demo(1, nb_var)