Search code examples
vbavbscriptvb6

Is there a need to set Objects to Nothing


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

Solution

  • VB uses a mechanism called "reference counting" to determine if an object is ready for destruction.

    When object reference is stored in a variable, e.g. when you use the Set keyword, the reference counter on that object is incremented. When the variable goes out of scope, the reference counter is decremented.

    When the counter reaches zero, the object is ready for destruction. The object resources will be released as soon as this happens.

    A function local variable will most likely reference an object whose reference counter never goes higher than 1, so object resources will be released when the function ends.

    When you pass the object to other functions, or store it in longer-lived objects, the reference counter will go higher than 1.

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

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

    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.