Loops and garbage collection

I am working on a web application and I came across 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 a = Nothing in a loop or will the garbage collector clear?

+4
source share
5 answers

In .NET, you usually don't need to set a variable reference = Nothing ( null in C #). In the end, the garbage collector will clean up. The link itself will be destroyed when it goes beyond the scope (either when your method completes, or when the object of this class is completed.) Note that this does not mean that the object destroyed, link to it. The object will continue to be destroyed non-deterministically by the collector.

However, setting your link = Nothing will give .NET a hint that the object may be garbage and does not necessarily harm anyone - other than code clutter. If you left it there, I would recommend removing it from the Try block; it is already in the Finally block and therefore will always be called. (Apart from some catastrophic exceptions, but in those cases it will not be called in the Try block!)

Finally, I have to admit that I agree with Greg: your code will be cleaner without it. The runtime hint you made with the link is good, but certainly not critical. Honestly, if I saw this in a code review, I would probably rewrite it like this:

 Dim a as Object Dim i as Integer = 0 For i=1 to 5 a = new Object() 'Do stuff Next 
+12
source

Almost never need to explicitly assign Nothing to a variable. The task of the garbage collector is to take care of the allocation of memory for you, in particular, to free you from this responsibility. No, you do not need to assign a = Nothing inside the loop.

You also don't need a try/finally block that assigns nothing around everything. This is actually just an extra mess that the system will take care on time.

+5
source

No, you do not need it .. NET has garbage collection. And since this code seems to be in the method area, garbage collection will clear any local variables.

+2
source

GC will clear it.

0
source

Like all of the above, you do not need to explicitly point variables to anything, since they are processed automatically. However, if for some reason you want to force the GC to build, you can run this:

 System.GC.Collect() 
0
source

Source: https://habr.com/ru/post/1277507/


All Articles