Garbage collection

  • JavaScript has automatic garbage collection.

  • The execution environment is responsible for managing the memory used during code execution.

  • The garbage collection mechanism works by finding memory that is no longer in use and freeing it. The garbage collector performs this operation periodically at regular intervals.

Mark clear

  • The most common form of garbage collection in JavaScript is tag scavenging.

  • The garbage collector runs by marking all variables stored in memory. It then unflags variables in the environment and those referenced by variables in the environment.

  • Variables tagged after this point are considered to be ready for deletion because they are no longer accessible to variables in the environment.

  • Finally, the garbage collector completes the memory cleanup. Different browsers have different garbage collection intervals.

  • Values that leave scope are automatically marked as recyclable and therefore deleted during garbage collection.

Reference counting

  • Another, less common garbage collection strategy is called reference counting. The meaning of reference counting is to keep track of how many 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 the value is 1. If the same value is assigned to another variable, the number of references to the value is increased by one. If one of the variables takes another value, the number of references to that value is reduced by one.

  • When the number of references to the value becomes zero, there is no way to access the value.

  • The next time the garbage collector runs, it frees the memory occupied by values with zero references.

Refer to the article

This article mainly refers to the third edition of JavaScrip Advanced Programming

Talk about JS garbage collection