Nic*_*pat 18 vbscript resource-cleanup
如果我使用设置变量CreateObject(),是否需要通过将其设置为Nothing使用后进行清理?
Dim foo
Set foo = CreateObject("SomeAssembly")
foo Bar
Set foo = Nothing
Run Code Online (Sandbox Code Playgroud)
脚本引擎会在超出范围时自动清除这些变量,因此在它们超出范围之前清除它们似乎毫无意义.
Eri*_*ert 31
如果我使用CreateObject()设置变量,是否需要在使用后将其设置为Nothing来清理它?
通常情况下你没有,但它已成为你所做的VB社区的绝杀.如果你是一个超级明星的人,那么通过设置变量来避开邪恶的眼睛并没有什么坏处Nothing,但它很少有帮助.
您确实需要设置变量的极少数情况Nothing是:
如果我不属于其中一种情况,我不会将变量设置为Nothing.我从来没有遇到过这个问题.
Ant*_*nes 13
我很少这样做: -
Set foo = Nothing
Run Code Online (Sandbox Code Playgroud)
这就是为什么......
考虑:-
Function DoStuff()
Dim foo : Set foo = CreateObject("lib.thing")
''# Code that uses foo
Set foo = Nothing
End Function
Run Code Online (Sandbox Code Playgroud)
由于foo即将传递出的范围反正分配Nothing到foo是多余的,所以我不打扰.
考虑:-
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
Run Code Online (Sandbox Code Playgroud)
现在,这是一种分配Nothing有意义的情况,因为否则它的持续时间可能比必要的时间长得多. 但是在这种情况下,代码是重构的候选者.事实上该函数继续做更多不需要的东西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
Run Code Online (Sandbox Code Playgroud)
在某些情况下,Nothing为了内存释放目的而分配是可取的,但我倾向于在特殊情况下这样做.在普通代码中,我发现它很少需要.
也许背后的"始终将不了了之"阵营的车手之一,是许多VBScripters写一些不受因素早已进入连续的脚本Function和Sub程序.