Difference between setting reference=null and going out of scope?

5 views
Skip to first unread message

Adam Clauss

unread,
Jun 24, 2004, 11:26:44 AM6/24/04
to
Basically, my question is in terms of performance and the garbage collector -
Is there any difference between
a) letting a variable simply go out of scope
b) explicity setting it to null once I am done with it

I have no particular reason to think that b) would gain me anything, but I thought maybe it would be a sure sign to the garbage
collector that Yes, you can go ahead and remove the object.

Thanks!

--
Adam Clauss
cab...@tamu.edu


Jon Skeet [C# MVP]

unread,
Jun 24, 2004, 11:49:29 AM6/24/04
to
Adam Clauss <cab...@tamu.edu> wrote:
> Basically, my question is in terms of performance and the garbage collector -
> Is there any difference between
> a) letting a variable simply go out of scope
> b) explicity setting it to null once I am done with it

Yes - explicitly setting it to null might take slightly longer, if the
JIT doesn't notice that the write is useless.

Actually, when running under a debugger there'll be a difference in
that the object (assuming there are no other references to it) will be
eligible for garbage collection from the point at which the variable is
set to null, compared with having to actually wait for it to go out of
scope. In release mode, it doesn't even have to wait to go out of scope
or be set to null - after the last use of it, the GC won't treat it as
a live reference.

> I have no particular reason to think that b) would gain me anything,
> but I thought maybe it would be a sure sign to the garbage
> collector that Yes, you can go ahead and remove the object.

Nope.

--
Jon Skeet - <sk...@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Adam Clauss

unread,
Jun 24, 2004, 12:53:22 PM6/24/04
to
Interesting, alright, thanks for the info.

--
Adam Clauss
cab...@tamu.edu
"Jon Skeet [C# MVP]" <sk...@pobox.com> wrote in message news:MPG.1b4508636...@msnews.microsoft.com...

Reply all
Reply to author
Forward
0 new messages