Set the variable to null as soon as possible?
Most developers who use C ++ have developed a good habit of releasing resources as soon as possible. After being transferred to the DOTNET platform, they must always set the used referenced variables to null, so that GC can reclaim memory as soon as possible. Is that true?
The GC of DOTNET is generational, which currently has four generations. The longest lifetime is in the first generation, and the shortest is also in the fourth generation. The fourth generation has little space, less than 1 MB. GC starts a collection only when it fails to allocate memory. The vast majority of the collection takes only the fourth generation. Because of its small space, the collection takes little time.
Take the followingCodeFor example:
Void Foo ()
{
String STR = datetime. Now. tostring ();
Console. writeline (STR );
STR = NULL;
For (INT I = 0; I <10; I ++)
Console. writeline (I );
}
In debug mode, the lifetime of STR is constructed to the end of the above function. Setting STR null can make the object suitable for recycling in advance. However, in release mode, the lifetime of STR is only after the console. writeline () parameter is calculated, that is, STR = NULL is completely redundant, and the compiler will optimize it.
Therefore, setting NULL for used local variables is futile.
However, for classes that implement the idisposable interface, it is meaningful to set the referenced data member to null in dispose. Although the object has been dispose, there may be references to this object, so that it cannot be recycled yet.