VBA 垃圾收集器详细信息 [英] VBA Garbage Collector Details

查看:27
本文介绍了VBA 垃圾收集器详细信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己最近不得不编写一些 VBA 代码,只是想知道是否有人遇到过有关 VBA 垃圾收集器如何工作的任何细节?.Net GC 确实有很好的文档记录,但除了模糊地提到它是一个参考计数器之外,我找不到关于 VBA GC 的任何细节.我认为它与 VB6 GC 非常相似,但也找不到任何相关信息.

具体来说,我有兴趣了解:

  • 什么触发了 GC
  • 它使用什么算法(例如,是集合生成的吗?)
  • 它如何(如果有的话)处理循环引用?
  • 有什么方法可以监控其运行情况

这更多是出于好奇而不是任何特别需要知道,非常感谢任何见解!

解决方案

以下假设 VBA 仍然使用 VB6 中使用的相同垃圾收集机制(它很可能会这样做).

VB6 使用了引用计数 GC.当对给定对象的最后一个引用设置为 Nothing 时,GC 会被确定性地触发.将本地引用设置为 Nothing 是不必要的,当它们超出范围时会发生这种情况.

每个对象都实现了一个 COM 接口,负责处理该对象的引用计数.对象引用的每次赋值都会更新相关引用的引用计数器(即,先前引用的旧对象的计数器递减,而新对象的计数器递增).当一个对象的引用计数器达到 0 时,它就会被垃圾回收.

因此在 VBA 应用程序的生命周期内永远不会收集循环引用中的对象.更重要的是,VBA 没有提供中断循环引用的方法.在VB6中,弱引用可以通过WinAPI函数实现.

I've found myself having to write some VBA code recently and just wondered if anyone had ever come across any details on how the VBA garbage collector works? The .Net GC is very well-documented indeed but I can't find a single shred of detail on the VBA GC, other than that vague mentions that it's a reference counter. I assume that it's pretty similar to the VB6 GC but can't find any information on that either.

Specifically, I'd be interested in knowing:

  • What triggers a GC
  • What algorithm it uses (is collection generational, for example?)
  • How (if at all) does it handle circular references?
  • Is there any way of monitoring its operation

This is more out of curiosity than any particular need to know, any insight at all much appreciated!

解决方案

The following assumes that VBA is still using the same garbage collection mechanism used in VB6 (which it very probably does).

VB6 used a reference-counting GC. The GC is triggered deterministically when the last reference to a given object is set to Nothing. Setting local references to Nothing is unnecessary, this happens as they go out of scope.

Every object implements a COM interface that takes care of the reference count for that object. Each assignment of an object reference updates the reference counters of the involved references (i.e. the counter of old object that was previously referenced gets decremented, and the new object’s counter is incremented). An object is garbage collected when its reference counter reaches 0.

Objects in circular references are thus never collected during the lifetime of a VBA application. What’s more, VBA doesn’t offer a way to break circular references. In VB6, weak references could be implemented via WinAPI functions.

这篇关于VBA 垃圾收集器详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆