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

  • Thread starter Thread starter Adam Clauss
  • Start date Start date
A

Adam Clauss

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 said:
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.
 
Back
Top