Set the variable to null as soon as possible?

Source: Internet
Author: User
Tags dotnet
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.