js garbage collection and memory leaks

js garbage collection

  • js application can be automatically recovered without the use of memory, due to the larger needs of each purge performance, not always refresh, but only once every so often.
  • Recovery of two ways
    • Clear flag (used) in the first tag memory variables, those variables and then remove those markers into the environment or referenced, exits into the environment when the environment, will be re-marked and cleared, the memory is released.
    • Calculating the number of reference count variable is referenced, the reference number 0 is cleared to release the memory. Disadvantages:
      • Those citations can not be cleared is not 0, but does not require memory
         let arr = [1,2,3];
         console.log('ok');
         //数组[1,2,3]引用次数为1,但是又没用到就会一直占着内存
         //解决方式:arr.length=0
      
      • Not solve the problem of circular references
          function fn(){
              let obj1 = {};
              let obj2 = {};
              obj1.a = obj2;
              obj2.b = obj1;
          }
          //解决方法:手动释放 obj1 = null obj2 = null
      

Memory Leak

  • Some cases can not release the memory, it has been in a variable environment
  • Memory leak occurs in some cases
    • The most common is the closure of
      • Closures will create a stack memory will not be destroyed.
      • Inadvertently global variables
          function fn(){
              obj = {};//没用声明关键字,相当于创建了一个全局变量
          }
      
      • The timer is not cleared
          setInterval()
          setTimeout()
          //解决方法
          清除对应定时器的id
Funny Face

Guess you like

Origin www.cnblogs.com/angle-xiu/p/11614316.html