The introduction

JavaScript Advanced Programming Edition 4 on garbage collection, I personally thought that the tag cleanup was in the dark until I came across this article:

Garbage collection

Garbage Collection

If you are interested in reading the original text, I will describe it in my own words and add some expansions.

Thank you for correcting any mistakes. 🌟 🌟

What is garbage

First we need to know what garbage is.

What is rubbish?

Objects that are no longer needed now or in the future are garbage. It’s the same thing in the program.

The article has a term called accessibility.

A value is considered reachable if any other value can be accessed from the root through a reference or chain of references

That means you can no longer access its data, so it’s unreachable.

Data that is not reachable can be recycled.

The logic is so simple and violent that you can’t even access it, so there’s really no need to ask for it.

Of course, a global variable can be accessed at any time, so it’s reachable, and it can’t be garbage.

Second, the functions that are being executed, such as this

function fn(){
  var b=2
  console.log(b)
}
fn()
Copy the code

When the function is executed, the data for B is generated, and it is reachable and cannot be deleted.

However, when the function is finished, it can no longer be accessed, at which point it is unreachable and needs to be deleted.

So here’s the conclusion:

  • Variables in the global environment are not garbage and cannot be recycled because they are reachable.

  • Variables in the local environment are garbage that can be recycled because they are no longer reachable.

But everything can be changed.

Refer to transfer

Single variable name reference transfer

// User has a reference to this object
let user = {
  name: "John"
};
Copy the code

The above code looks like this in memory

This is a global variable, and it is likely to be used by other code, so it cannot be recycled.

However, when the user variable name reference changes

user = null
Copy the code

The original {name:John} data can not access it, then can be recycled.

But if the code looks like this

let user = {
  name: "John"
};
let admin = user
user = null
Copy the code

At this point {name:John} can still be accessed through the admin variable, and it cannot be reclaimed.

Objects that are interrelated

Here’s a more complex object

function marry(man, woman) {
  woman.husband = man;
  man.wife = woman;

  return {
    father: man,
    mother: woman
  }
}

let family = marry({
  name: "John"
}, {
  name: "Ann"
});
Copy the code

So the memory graph looks like this

If this code is executed at this point

delete family.father;
delete family.mother.husband;
Copy the code

It’s going to look like thisAt this time{name:John}No longer reachable, then it’s recycled.

So, according to the memory map, if you reference the family variable name somewhere else.

family = null;
Copy the code

Obviously, if the original data is no longer reachable, it will be reclaimed.

Garbage collection strategies

Above is the basic concept of garbage collection, very realistic logic.

Here’s the strategy

Mark sweep

Periodically perform the following “garbage collection” steps, starting with this data

1. The garbage collector finds all the roots by walking through them and “marks” (remembers) them.2. If the referenced data is available, it is reachable. Mark all the way to the last layer reference.3. If you find a data that is never referenced by the root (which is accessible by the global variable), recycle it.

Of course, while traversing, due to the large amount of data, in order not to affect the JS code operation and speed up the garbage collection, some optimization (including but not limited to) has been done.

  • Generational collection

Popularizing is dividing data into two types, Cenozoic and Paleozoic. Some functions have variables that can be garbage collected quickly, while variables that have not been garbage collected for a long time will change from new to old and may never be deleted, so reduce the frequency of checking them with garbage collection. —- Reduces the number of periodic traversals of certain data

  • Incremental collection

Collect slowly, expanding the scope of your garbage collection rather than going through it all at once. —- Reduce the range of collection and increase the amount of traversal

  • Spare time to collect

This is very common, let the JS code go first and collect the garbage when it’s free

Reference counting (extension)

The little Red Book of this respect is quite clear

Another garbage collection strategy that is not commonly used is reference counting. The idea is to keep track of how many times each value is referenced.

When you declare a variable and assign it a reference value, the number of references to that value is 1. If the same value is assigned to another variable, the number of references is increased by one. Similarly, if the variable holding a reference to that value is overwritten by another value, the number of references is reduced by one. When the number of references to a value is zero, the value can no longer be accessed, so its memory can be safely reclaimed. The next time the garbage collector runs, it frees memory for the zero reference value.

There’s a big problem with reference counting, though: if you’re referencing each other, The Times add up

function fn(){
  var a=1
  var b=a
}
fn()
Copy the code

At this point, variable A is recorded as twice referenced and is not garbage collected even if the function completes.

Closures (extensions)

Notice that the above example didn’t talk about closures, but I personally think of closures as global variables.

The following is an excerpt from Nguyen Yifeng’s blog

Closures can be used in many ways. It is useful for reading variables inside functions, as mentioned earlier, and for keeping their values in memory at all times.

Closures occur when a function is referenced by a variable outside of the current function’s scope. Closures are of course not recycled unless the external variable is released.

Here’s an example:

function f1(){var n=999; nAdd=function(){n+=1}function f2(){alert (n); }returnf2; }var result=f1();// The result is obtainedresult();/ / 999NAdd bring them any closer (); result();/ / 1000
Copy the code

The above data n is in the function, but it will still be stored in memory.

If nAdd’s reference to result is not released, data n is not garbage collected.

conclusion

  • Garbage collection is automatic and cannot be enforced or prevented.
  • When an object is reachable, it must exist in memory.
  • Being referenced is not the same as being accessible (from a root) : a set of interconnected objects may not be reachable as a whole.

The last 🌟 🌟

So that’s my simple share of garbage collection.

If you think it is helpful to you, please click “like”, thank you!

End scatter flower! 🌸 🌸 🌸

github

Finally, I would like to promote the Github blog that I maintain for a long time

1. From learning to summary, record important knowledge points of the front-end, including in-depth Javascript, HTTP protocol, data structure and algorithm, browser principles, ES6, front-end skills, etc.

2. There is a directory in the README to find relevant knowledge points.

If it is helpful to you, welcome star and follow.

The address is here