是否有必要设置对象为Nothing VBA函数里面 [英] Is there a need to set Objects to Nothing inside VBA Functions

查看:551
本文介绍了是否有必要设置对象为Nothing VBA函数里面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是读这是建议设置对象不了了之,一次我跟他们做。但我通常使用它们只是在功能里面的形式。

是不是失去了参考和内存释放时的作用范围是左的,不管对象设置为Nothing?

即。是不是真的有必要做的:

 设置分贝=什么
设置record_set =什么
 

解决方案

VB采用的是所谓的引用计数垃圾收集器。

基本上,一个变量超出范围的那一刻,被引用的对象的引用计数器递减。当你的对象引用赋值给另一个变量时,引用计数器就会增加。

当计数器达到零,对象是准备进行垃圾回收。在对象资源将尽快出现这种情况公布。函数局部变量将最有可能引用一个对象的引用计数永远不会大于1,所以对象的资源将被释放函数结束时。

设置变量没有是明确地减小引用计数器的方式。

例如,你在一个文件中读取,并将该文件对象变量设置为没有之后的 ReadAll方法()调用。该文件句柄将被立即释放,你可以把你的时间过程及其内容。

如果您没有设置为没有,该文件句柄可能会开放长于绝对必要的。

如果你不是一个必须解除宝贵资源这种情况,只是让变量走出去的范围是好的。

I always read that it is recommended to set objects to nothing, once I am done with them. But I normally use them only in functions inside forms.

Isn't the reference lost and memory released when the function scope is left, regardless of setting objects to Nothing?

i.e. is it really necessary to do:

Set db = Nothing
Set record_set = Nothing

解决方案

VB uses a so-called "reference counting" garbage collector.

Basically, the moment a variable goes out of scope, the reference counter on the referenced object is decremented. When you assign the object reference to another variable, the reference counter is incremented.

When the counter reaches zero, the object is ready for garbage collection. The object resources will be released as soon as this happens. A function local variable will most likely reference an object whose reference count never goes higher than 1, so object resources will be released when the function ends.

Setting a variable to Nothing is the way to decrease the the reference counter explicitly.

For example, you read in a file, and set the file object variable to Nothing right after the ReadAll() call. The file handle will be released immediately, you can take your time process its contents.

If you don't set to Nothing, the file handle might be open longer than absolutely necessary.

If you are not in a "must unblock valuable resource" kind of situation, simply letting the variables go out of scope is okay.

这篇关于是否有必要设置对象为Nothing VBA函数里面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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