Question 42: what is the JS garbage collection mechanism?


JS memory life cycle

  1. Allocate the memory you need

  2. Use allocated memory (read, write)

  3. Release and return them when they are not needed

What is garbage collection mechanism?

The garbage collection mechanism is to find out those values that are no longer used, and then release the memory space occupied by them. The garbage collector performs a release operation every fixed period of time

What are the ways in which garbage collection is performed?

Mark clear

  • The memory occupied by variables “entering the environment” cannot be released. As long as the execution flow enters the corresponding environment, they may be used. When a variable leaves the environment, it is marked as “leaving the environment”

  • There are many ways to mark: flip a special bit to record when a variable enters the environment; Use a “enter environment” variable list and a “leave environment” list

  • When the garbage collector runs, it will mark all variables. Then, the marks on the variables in the environment and the variables referenced by the variables in the environment will be removed

  • After that, the variables marked will be regarded as the variables to be deleted, because the variables in the environment can no longer access these variables

  • Finally, the garbage collector completes the memory cleanup, destroying the marked values and reclaiming the memory space they occupy

Reference count
Track the number of times each value is referenced

  • When a variable is declared and a reference type value is assigned to the variable, the number of references to this value is 1

  • If the same value is assigned to another variable, the number of references to the value is increased by 1

  • Conversely, if the variable containing the reference to this value gets another value, the number of references to this value is reduced by 1

  • When the number of references of this value becomes 0, it means that there is no way to access this value again, so the memory space occupied by it can be reclaimed

  • In this way, when the garbage collector runs again the next time, it will free up the memory occupied by values with zero references

  • If circular references will not be cleared in ie, they must be cleared manually. Failure to do so will result in memory leaks

The content / inspiration of the article is drawn from the following content

Recommended Today

Hive built-in function summary

1. Related help operation functions View built-in functions: Show functions; Display function details: desc function ABS; Display function extension information: desc function extended concat; 2. Learn the ultimate mental method of built-in function Step 1: carefully read all the functions of the show functions command to establish an overall understanding and impression Step 2: use […]