Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a need to set Objects to Nothing

Tags:

vba

vb6

vbscript

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 
like image 885
Ramon Avatar asked Feb 05 '09 17:02

Ramon


People also ask

What does is nothing do in VBA?

Summary. Doing nothing in VBA is as simple as not writing any code, or re-routing the flow of code so that you skip all the things that otherwise the code would have done.

How do you set a variable to nothing in VBA?

Assigning Nothing To free an object variable so that it no longer points to anything, assign the "Nothing" keyword. (eg Set rgeRange = Nothing). It is good programming practice to free object variables when they are no longer needed, since this can save resources.


1 Answers

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.

like image 160
Tomalak Avatar answered Oct 02 '22 21:10

Tomalak