current position:Home>JavaScript garbage collection mechanism

JavaScript garbage collection mechanism

2021-08-26 23:38:51 Shang Silicon Valley iron powder

brief introduction

JS With a memory management engine , Responsible for creating objects 、 Destroy object , And garbage collection . In this issue, we will discuss the garbage collection mechanism . Garbage collection mechanism is mainly composed of a garbage collector (garbage collector, abbreviation GC) The background process of is responsible for monitoring 、 Clean up objects , And reclaim the free memory in time .

and C#、Java equally JavaScript There is an automatic garbage collection mechanism , That is to say, the execution environment is responsible for managing the memory used during code execution , In the development process, there is no need to consider the problems of memory allocation and recycling of useless memory .
and JavaScript Creating objects ( object 、 String, etc. ) It allocates memory for them , Don't use timing anymore “ Automatically ” Free memory , This process is called garbage collection .

Every stage in the memory life cycle :

Allocate memory —  Memory is allocated by the operating system , It allows your program to use it . In low-level language ( for example C Language ) in , This is an explicit operation that developers need to handle by themselves . However , In advanced languages , The system will automatically assign you inner .
Using memory — This is the memory allocated before the program actually uses it , When using assigned variables in code , There will be read and write operations .
Free memory — Free up all memory that is no longer in use , Make it free memory , And can be reused . It's the same as allocating memory , This operation also needs to be performed explicitly in low-level languages .

Four common memory leaks : Global variables , Timer not cleared , Closure , as well as dom References to

  1. Global variables no need var Declared variables , Equivalent to mounting to window On the object . Such as :b=1; solve : Using strict mode
  2. Forgotten timer and callback functions
  3. Closure
  4. Not cleaned up DOM Element reference

Want to know more   Front end training Develop technical knowledge . Pay attention to me , There are more wonderful contents to share with you !

copyright notice
author[Shang Silicon Valley iron powder],Please bring the original link to reprint, thank you.

Random recommended