1. Manage memory

Js memory allocation

When writing JavaScript programs, developers no longer care about memory usage, and the allocation of required memory and the collection of unused memory are fully managed automatically.

Memory declaration cycle:
  1. Allocate as much memory as you need
  2. Use allocated memory (read, write)
  3. Release \ return it when it is not needed

Because strings, objects, and arrays have no fixed sizes, they can only be allocated dynamically when their sizes are known. Every time a JavaScript program creates a string, array, or object, the interpreter must allocate memory to store that entity.

Whenever memory is allocated dynamically like this, it must eventually be freed so that it can be reused, otherwise the JavaScript interpreter will consume all available memory in the system, causing the system to crash.

2. Concept of garbage collection mechanism

The definition of garbage collection is given in MDN:

JavaScript automatically allocates memory when variables (objects, strings, etc.) are created and “automatically” frees them when they are not used, a process called garbage collection.

Javascript has an automatic GC:Garbage Collecation, which means that the execution environment is responsible for managing the memory used during code execution.

The idea is that the garbage collector periodically (periodically) finds variables that are no longer in use and then frees their memory. However, this process is not real-time because it is expensive and stops responding to other operations during GC.

Garbage collection algorithms rely heavily on the concept of references. In a memory-managed environment, an object refers to another object if it has access to another object (implicitly or explicitly).

The most common examples of garbage collection are tag removal and reference counting.

2.1 Mark Clearing

Since 2012, all modern browsers have used the mark-sweep garbage collection algorithm. All of the improvements to JavaScript garbage collection algorithms are based on improvements to the mark-sweep algorithm, not on improvements to the mark-sweep algorithm itself and its simplified definition of whether an object is no longer needed.

When a variable enters the execution environment, it is marked as “enter environment”. Logically, you should never free up memory occupied by variables that enter the environment, because they may be used whenever the execution stream enters the corresponding environment. When a variable leaves the environment, it is marked “out of the environment.”

The garbage collector runs by marking all variables stored in memory. It then removes variables in the environment and tags 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, destroying the tagged values and reclaiming the memory they occupy. Tag sweep is the most important garbage collection method in JavaScript, and so far, JS implementations of IE9+, Firefox, Opera, Chrome, and Safari all use tag sweep garbage collection or similar strategies, with different garbage collection intervals.

Here is an example of freeing memory:

function addTen(num){ var sum += num; Garbage collection has marked this variable as "entering the environment". return sum; Garbage collection has marked this variable as "out of environment". } addTen(10); / / output 20Copy the code

When you run the addTen function, mark the variable as “entering the environment.” Logically, you can never release the memory occupied by variables entering the environment, because they may be used whenever the execution stream enters the corresponding environment. When a variable leaves the environment, it is marked as “out of the environment.”

The garbage collector runs by marking all variables stored in memory. It then unmarks 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, destroying the tagged values and reclaiming the memory they occupy.

2.2 Reference Counting

Reference counting is the most rudimentary garbage collection algorithm and is not commonly used. Reference counting keeps track of how many times each value is referenced. When a variable is declared and a reference type is assigned to the variable, the number of references to the value is 1. Conversely, if the variable containing a reference to that value obtains another value, the number of references to that value is reduced by one.

When the number of references becomes zero, there is no way to access the value, so it can be reclaimed. This way, the next time the garbage collector runs, it frees the memory occupied by values that are referenced zero times.

This method will result in loop cross-references not being released, and will result in memory leaks if a large number of them exist.

function f(){ var o = {}; var o2 = {}; o.a = o2; // o reference o2 o2. A = o; O return "azerty"; } f();Copy the code

In the code above, two objects o, O2 are created, and o and O2 refer to each other, forming a loop. They leave the scope of the function after being called and can be reclaimed, but the reference-counting algorithm considers that they all have at least one reference to each other, so they are not reclaimed.

On the other hand, in the early Internet Explorer browser, the garbage collection mechanism of COM objects adopts the reference counting strategy. Only COM objects involved in Internet Explorer, there will be the problem of circular reference. To avoid such circular references, it is best to disconnect the native JavaScript object from the native DOM element by manually setting it to null when they are not in use.

3. Performance problems

The garbage collector runs periodically, and if the amount of memory allocated for variables is significant, the collection effort can be considerable. In this case, determining the time interval for garbage collection is a very important issue.

With the release of IE7, thresholds for variable assignments, literals, and array elements that trigger garbage collection have been adjusted to dynamic correction. This simple tweak dramatically improves performance when running pages with a lot of JavaScript.

4. To summarize

JavaScript variables can be used to hold values of two types: base and reference types, which have the following characteristics:

Values that leave scope are automatically marked as recyclable and deleted during garbage collection; “Tag sweep” is the current mainstream garbage collection algorithm. The idea of this algorithm is to mark the value that is not currently used and then reclaim its memory. The “reference counting” algorithm causes problems when there are circular references in the code; Dereferencing variables not only helps eliminate circular references, but also benefits garbage collection. To ensure efficient reclaimed memory, global variables, global object attributes, and circular reference variables that are no longer used should be de-referenced in a timely manner.