Alex Rivera | Logout

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

Asked 2011-11-15T23:07:03.277
23

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

Dim foo
Set foo = CreateObject("SomeAssembly")
foo Bar
Set foo = Nothing

I just found this post by Eric Lippert:

The script engine will automatically clear those variables when they go out of scope, so clearing them the statement before they go out of scope seems to be pointless.

Edit
Report

1 Answer

16

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.

answered 2011-11-16T13:20:25.980

Your Answer