Javascript garbage collection mechanism

Source: Internet
Author: User

Javascript has an automatic Garbage Collection mechanism (GC: Garbage Collection ). The mechanism of this garbage collection mechanism is simple: Find out the variables that are no longer in use, and then release the memory occupied by them. The garbage collector periodically performs this operation at a fixed interval.

The most common method of garbage collection in javascript is mark-and-sweep ). When a variable enters the environment, it is marked as "entering the environment", and when the variable leaves the environment, it is marked as "leaving the environment ". Variables marked with "Exit environment" will be deleted from the occupied space when the garbage collector performs an operation. In short,GC automatically recycles objects that are not referenced..

Instance 1:

function func(){  var arr= ["value1","value2"];  return arr;}var m = func();alert(m);//value1,value2

In the func function, local variables (arr) are not necessarily recycled immediately after the function is returned. Instead, they are recycled only after they are no longer referenced! Because m always references this array. However, once m = null is manually set, the array will be automatically recycled because no reference is provided.

Instance 2:

Function outerFunc () {var num = 10; function innerFunc () {num * = 2; return num;} return innerFunc ;} // assign the innerFunc function to refInnerFuncvar refInnerFunc = outerFunc (); refInnerFunc (); // return 20 variable num still exists in the memory and can be accessed and modified by innerFunc (); // return 40

After the outerFunc () function is executed, the local variable num is not recycled by GC, but is stored in memory because reference to num is always saved in innerFunc, therefore, num will not be recycled by GC.

 

 

Related Article

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.