Delete Objects

mafrosis

Well-known member
Joined
Jun 5, 2006
Messages
88
Location
UK
Programming Experience
5-10
Hey all,

A simple question really - if I create an object to use very breifly and then discard, is there any need for the final line in this code?

VB.NET:
[COLOR=Blue]Dim[/COLOR] wsi [COLOR=Blue]As New[/COLOR] WorkStreamInst([COLOR=Blue]Me[/COLOR].workstream_id, [COLOR=Blue]Me[/COLOR].workstream_rev)
[COLOR=Blue]Me[/COLOR].data_class = wsi.data_class
[COLOR=Blue]Me[/COLOR].sp_prefix = wsi.sp_prefix
[COLOR=Blue]Me[/COLOR].ui_control = wsi.ui_control
[COLOR=Blue]Me[/COLOR].auth_control = wsi.auth_control
[COLOR=Blue]Me[/COLOR].unit_of_work = wsi.unit_of_work
wsi = [COLOR=Blue]Nothing   [/COLOR][COLOR=SeaGreen]'needed?[/COLOR]
Im not sure if setting my object to Nothing actually makes any difference with the GC?

Thanks
mafro
 
It depends on the context and scope, GC won't try to release the object until after the variable goes out of scope, when sub/function method is finished and local variable don't exist anymore, and even then it is unknown exactly when GC will do its job, it will but perhaps not immediately.

When you set this variable to nothing at least references to the resources it may hold is released, and the variable goes from strongly acquired memory to loosely allocated memory for its type, in which case the background GC can temporarily allow to release this part of the applications allocations.

Its a similar issue with the Dispose functionality, while this works through more layers of memory allocations, allowing signaling to child objects that implements the IDisposable interface to react and also free their allocations instead of just being left in the open to be collected later by GC.

So you should use Dispose when the object provides this (sometimes it is coupled with Close method), and if in the middle of a method process where you will not be using the variable again it could also benefit to set the object to Nothing afterwards.
 
Back
Top