Loops and Garbage Collection

2019-02-18 10:12发布

I am working on a web application and I have run into the following situation.

Dim a as Object
Dim i as Integer = 0

Try

    For i=1 to 5

        a = new Object()

        'Do stuff '

        a = Nothing

    Next

Catch

Finally

   a = Nothing

End Try

Do i need to do the a=Nothing in the loop or will the garbage collector clean a up?

5条回答
\"骚年 ilove
2楼-- · 2019-02-18 10:51

In .NET, you generally do not need to set a variable reference = Nothing (null in C#). The garbage collector will clean up, eventually. The reference itself will be destroyed when it goes out of scope (either when your method exits or when the object of this class is finalized.) Note that this doesn't mean the object is destroyed, just the reference to it. The object will still be destroyed non-deterministically by the collector.

However, setting your reference = Nothing will provide a hint to .NET that the object may be garbage, and doesn't necessarily hurt anything -- aside from code clutter. If you were to keep it in there, I'd recommend removing it from Try block; it's already in the Finally block and will therefore always be called. (Aside from certain catastrophic exceptions; but in those cases it wouldn't get called in the Try block either!)

Finally, I have to admit that I agree with Greg: Your code would be cleaner without this. The hint to the runtime that you're done with the reference is nice, but certainly not critical. Honestly, if I saw this in a code review, I'd probably have the developer rewrite it thusly:

Dim a as Object
Dim i as Integer = 0

For i=1 to 5
    a = new Object()
    'Do stuff
Next
查看更多
时光不老,我们不散
3楼-- · 2019-02-18 10:51

Like everyone stated above you do not need to explicitly set your variables to nothing, as it is handled automatically. However, if for whatever reason you want to force the GC to collect, you can run this:

System.GC.Collect()
查看更多
The star\"
4楼-- · 2019-02-18 10:56

The GC will clean it up.

查看更多
闹够了就滚
5楼-- · 2019-02-18 10:57

It is almost never necessary to explicitly assign Nothing to a variable. The garbage collector's job is to take care of memory allocation for you, specifically to relieve you of this responsibility. So no, you don't need to assign a = Nothing inside the loop.

You also do not need the try/finally block that assigns Nothing around the whole thing. This is really just extra clutter that the runtime system will take care of anyway.

查看更多
Summer. ? 凉城
6楼-- · 2019-02-18 11:08

No you don't need it. .NET has garbage collection. And since it looks like this code is in a method scope the garbage collection will clean up any local variables.

查看更多
登录 后发表回答