Replies: 3 comments
-
This would be a runtime question, not a language question. In general I would think that the guideline would be that you shouldn't set your referencing to |
Beta Was this translation helpful? Give feedback.
-
As with all things performance related, the right approach is to measure and profile and make the changes if they benefit your scenario |
Beta Was this translation helpful? Give feedback.
-
I remember I read some blogs on this topic in the early days of .NET. The longer answer contains multiple reasons. Of what I still remember:
That being said, there could be special cases where it may help to null a reference: e.g. if you have some function like below: async Task LongRunningFunctionAsync()
{
var largeObject = new SomeLargeObject("xxx");
await UseItAync(largeObject);
// you may want to do this so that it can be GCed earlier, assuming the optimizer does not remove it
// largeObject = null;
await Task.Delay(2000); // take some time here, which will extend largeObject's life
largeObject = new SomeLargeObject("yyy");
await UseItAync(largeObject);
} But normally it happens in bad code, which should be refactored instead. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Many C# books tell us that it is not necessary to update the references in garbage objects to be null manually, as they will be reclaimed by GC later. This is true if we don't consider GC performance. But if we need consider GC performance, the answer might be different, as the current .NET GC is generational GC. If an object in Generation2 becomes garbage and it is referencing another garbage object in Generation0, then when next Gen0 GC happens, the garbage object in Gen0 can't be reclaimed as it is referenced by a Gen2 object, even though the Gen2 object itself is also garbage. We must wait until next Gen2 GC to reclaim these two objects at one time. But if we can update the reference in the Gen2 object from the Gen0 object to null when the Gen2 object itself becomes garbage, then the Gen0 object will be reclaimed in next Gen0 GC, much sooner than next Gen2 GC.
If my point of view is correct, then the C# GC documents/books should be updated to tell all C# users about it. Programmers need to update the references in garbage objects to be null manually to improve GC performance.
Beta Was this translation helpful? Give feedback.
All reactions