Vbscript 如果我使用`CreateObject()`设置变量,我是否需要在使用后通过将其设置为`Nothing`来清理它?

Vbscript 如果我使用`CreateObject()`设置变量,我是否需要在使用后通过将其设置为`Nothing`来清理它?,vbscript,resource-cleanup,Vbscript,Resource Cleanup,如果我使用CreateObject()设置变量,使用后是否需要将其设置为Nothing Dim foo Set foo = CreateObject("SomeAssembly") foo Bar Set foo = Nothing 我刚刚发现: 脚本引擎将在这些变量超出范围时自动清除它们,因此在它们超出范围之前清除语句似乎毫无意义 我很少这样做:- Set foo = Nothing 这就是为什么 考虑:- Function DoStuff() Dim foo : Set foo

如果我使用
CreateObject()
设置变量,使用后是否需要将其设置为
Nothing

Dim foo
Set foo = CreateObject("SomeAssembly")
foo Bar
Set foo = Nothing
我刚刚发现:

脚本引擎将在这些变量超出范围时自动清除它们,因此在它们超出范围之前清除语句似乎毫无意义

我很少这样做:-

Set foo = Nothing 
这就是为什么

考虑:-

Function DoStuff()
    Dim foo : Set foo = CreateObject("lib.thing")
    ''# Code that uses foo
    Set foo = Nothing
End Function
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
由于
foo
即将超出范围,因此为
foo
分配
Nothing
是多余的,所以我不想麻烦了

考虑:-

Function DoStuff()
    Dim foo : Set foo = CreateObject("lib.thing")
    ''# Code that uses foo
    Set foo = Nothing
End Function
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
现在,在这种情况下,分配
什么都不分配是有意义的,因为否则,它的保留时间可能比需要的时间长得多但是在这种情况下,代码是重构的候选对象。函数继续执行大量不需要
foo
的工作,这表明使用
foo
的代码块实际上属于它自己的函数:-

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
在某些情况下,出于内存释放的目的,分配给
Nothing
是可取的,但我倾向于在特殊情况下这样做。在普通代码中,我发现很少有必要这样做

也许“总是设置为零”阵营背后的驱动因素之一是许多VBScriptor编写的顺序脚本没有很好地考虑到
函数
子过程中

如果我使用CreateObject()设置变量,我是否需要在使用后将其设置为Nothing来清理它

Dim foo
Set foo = CreateObject("SomeAssembly")
foo Bar
Set foo = Nothing
通常情况下,您不会这样做,但您这样做已经成为VB社区的一个常识。如果你是一个超自然人,当你使用变量时,将变量设置为
Nothing
不会伤害到你避开邪恶的眼睛,但它也很少有帮助

极少数情况下,您确实需要将变量设置为
Nothing
,这些情况下:

  • 您创建了垃圾回收器无法清理的循环引用
  • 对象很昂贵,但变量的寿命很长,因此您希望尽早清理它
  • 对象实现需要必须维护的特定关闭顺序
  • 等等

如果我没有遇到这种情况,我不会将变量设置为
Nothing
。我从来没有遇到过这个问题。

如果您的变量是模块或全局变量(在模块顶部附近声明,在任何过程之外),那么该变量可能不会在脚本结束时自动超出范围。这可能会在某些情况下引起问题,所以您可以考虑将变量设置为零(或者如果它不是对象变量,则默认为默认值)。

如果我没有错,大多数循环引用都很容易清理。当COM对象(不是GCed)有一个循环引用时,会导致此问题。。。。许多VBScriptor编写的顺序脚本没有很好地分解到函数和子过程中是的!现在我知道了为什么在大型的旧VBScript项目中工作总是很困难。