This is the third day of my participation in Gwen Challenge

As MORE and more JS is used in side development (such as ELECTRON), the front end also needs to pay more attention to memory problems. Understanding the implementation of JS memory management can help us avoid writing code that has memory leaks.

JS has the following two automatic garbage collection mechanisms:

1. Mark clearing

Mark clearing means that when a variable enters an execution environment, it is marked as “in environment” and when it leaves as “out of environment”. This can be done in any way, and then, when the garbage collector (GC) runs, it can release variables marked “out of the environment.”

An example of any of the above is to mark all variables in memory, then clear the marks of variables referenced by variables in the environment, and finally reclaim variables that still have tags.

By 2008, major browsers were using a tag sweep (or similar) garbage collection strategy.

2. Reference count

Another method is reference counting. Each time a value is assigned to a variable, the number of references to that value is increased by one. When a variable pointing to that value takes another value, the number of references to the original value is decreased by one. Therefore, when the number of references is 0, the value is no longer used, and when the garbage collector runs, the memory space occupied by this value is reclaimed.

There is A serious problem with reference counting: circular references, where A pointer in object A points to B and B points to A, never have zero references and therefore are not recycled.

3. The enlightenment

Once we understand the JS memory management strategy, we can consciously avoid memory leaks when writing code, such as:

  • Do not store too many or too many values globally, as this disables token clearing and reference counting strategies, and variables cannot be reclaimed.
  • When large values are no longer in use, be careful to set the variable to NULL so that when the value is removed from the runtime, the memory is reclaimed by the GC.

Reference: The Little Red Book chapter 4 – Variables, scopes, and memory Problems