How Should I Release Variable Memory

MiloCold

Member
Joined
Mar 17, 2005
Messages
21
Programming Experience
Beginner
Greetings,

I've been reading on the various methods used to release memory/ manage it and frankly I'm a bit confused.

This is what I'm trying to accomplish:

My program starts off by declaring/defining some vars, opening a directory and grabing some text files. If no text files our found I would like the application to exit and release all variables properly for the GC.

Currently, I have a code segment at the very end the subprocedure that sets every variable equal to nothing (which I believe properly sets vars for GC), but I know a better exists. Any advice?

I think it would be great to pass "Me" as a parameter to a method that just cycles through any declared variables and disposes of them. However, I just can't find any info...and what I find is a bit over my head ;)

Thanks in Advance, I look forward to spending many long nights on this forum!

_Milo
 

JuggaloBrotha

VB.NET Forum Moderator
Staff member
Joined
Jun 3, 2004
Messages
4,524
Location
Lansing, MI; USA
Programming Experience
10+
just let the variable go out of scope (ie you dont have to do anything to dispose it, just stop using it) and the garbage collector will take care of the actual disposal of the variables
 

Ruffnekk

Member
Joined
Mar 17, 2005
Messages
17
Location
Rotterdam, Netherlands
Programming Experience
10+
I think it's a good habit to release variable memory in every function or sub to ensure optimal memory use. You can either use the Dispose member or set it to nothing. I can't think of a way to do it globally from the top of my head, unless you declare everything globally:

VB.NET:
Class MyClass

Public item1 As Object
Public item2 As Object
...

Sub Main()

End Sub

Sub NotSoMain()

End Sub

Sub DisposeAll()
  item1 = Nothing
  item2 = Nothing
End Sub
End Class
But this is very bad programming habit. In general it's advisable to use as little globals as possible and declare and dispose them locally whenever possible.
 

JuggaloBrotha

VB.NET Forum Moderator
Staff member
Joined
Jun 3, 2004
Messages
4,524
Location
Lansing, MI; USA
Programming Experience
10+
actually setting variables to nothing has no effect on memory usage, but with the garbage collector that's automatically called handles everything quite wonderfully as it is, the best way to release the memory for variables (and objects) is to simply let them go out of scope

ie: if a variable was declared in a sub/function procedure, when the procedure is complete the variable then falls out of scope and the garbage collection free's the memory
 
Top Bottom