当前位置:网站首页>How to manually implement the mechanism of triggering garbage collection in node

How to manually implement the mechanism of triggering garbage collection in node

2022-04-23 17:22:00 Grass like years

Refer to Ruan Yifeng ES6 Standard in getting started , Manual implementation

node --expose-gc // --expose-gc  Indicates that manual garbage collection mechanism is allowed 

Then execute the code :

//  Perform a garbage collection manually to ensure the accuracy of memory data 
> global.gc();
undefined

//  View the memory currently occupied , The main concern is heapUsed Field , It's about the size of 4.4MB
> process.memoryUsage();
{ rss: 21626880,
  heapTotal: 7585792,
  heapUsed: 4708440,
  external: 8710 }

//  Create a WeakMap
> let wm = new WeakMap();
undefined

//  Create an array and assign it to a variable key
> let key = new Array(1000000);
undefined

//  take WeakMap The key name of points to the array 
//  There are two references to the array , One is key, One is WeakMap Key name of 
//  Be careful WeakMap Is a weak reference 
> wm.set(key, 1);
WeakMap { [items unknown] }

//  Manual garbage collection once 
> global.gc();
undefined

//  Check the memory usage again ,heapUsed Has been increased to about 12MB
> process.memoryUsage();
{ rss: 30232576,
  heapTotal: 17694720,
  heapUsed: 13068464,
  external: 8688 }

//  Clear variables manually key Reference to array 
//  Notice that it's not cleared here WeakMap Reference of middle key name to array 
> key = null;
null

//  Recycle again 
> global.gc()
undefined

//  View memory usage , Find out heapUsed It's back to its previous size ( It's about 4.8M, Originally for 4.4M, Slightly floating )
> process.memoryUsage();
{ rss: 22110208,
  heapTotal: 9158656,
  heapUsed: 5089752,
  external: 8698 }

Link to the original text

版权声明
本文为[Grass like years]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231720179064.html