If I set a variable using `CreateObject()`, do I need to clean it up by setting it to `Nothing` after use?

If I set a variable using CreateObject(), do I need to clean it up by setting it to Nothing after use?

Typically you do not, but it has become lore in the VB community that you do. If you are a supersitious person, it doesn't hurt to ward off the evil eye by setting variables to Nothing when you are done with them, but it rarely helps anything either.

The rare cases where you do need to set a variable to Nothing are those cases where:

  • you have created a circular reference that the garbage collector is unable to clean up
  • the object is expensive but the variable is long-lived, so you want it to be cleaned up early
  • the object implementation requires a particular shutdown order that must be maintained
  • and so on.

If I'm not in one of those cases, I don't set variables to Nothing. I've never had a problem with that.


I rarely do this:-

Set foo = Nothing 

Here is why...

Consider:-

Function DoStuff()
    Dim foo : Set foo = CreateObject("lib.thing")
    ''# Code that uses foo
    Set foo = Nothing
End Function

Since foo is about to pass out of scope anyway assigning Nothing to foo is superfluous so I don't bother.

Consider:-

Function DoStuff()
    Dim foo : Set foo = CreateObject("lib.thing")
    ''# Code that uses foo
    Set foo = Nothing
    ''# Loads more code that doesn't use foo
End Function

Now this is a case where assigning Nothing makes sense since otherwise it's held for potentially a lot longer than is necessary. However in such cases the code is a candidate for refactoring. The fact that the function continues to do quite a lot more stuff not needing foo indicates that the foo-using chunk of code actually belongs in its own function:-

Function DoStuff()
    ''# Code that calls FooUsage
    ''# Loads more code that doesn't use foo
End Function

Function FooUsage(someParams)
    Dim foo : Set foo = CreateObject("lib.thing")
    ''# Code that uses foo
    FooUsage = someResult
End Function

There are occasions where assigning to Nothing for memory release purposes is advisable but I tend to do it in special cases. In normal code I find it's rarely necessary.

Perhaps one of the drivers behind the "Always set to nothing" camp is that many VBScripters write sequential scripts that are not factored well into Function and Sub procedures.