Node.js/内存:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
第266行: 第266行:
=== --expose-gc ===
=== --expose-gc ===
强制回收垃圾
强制回收垃圾
{| class="wikitable"
|1
|<code>$ node --expose-gc file.js</code>
|}
<br />
{| class="wikitable"
|1
|<code>global.gc();</code>
|}
<br />
{| class="wikitable"
|1
2
3


4
{{hc|test.js|<syntaxhighlight lang="javascript">/** * 单位为字节格式为 MB 输出 */
const format = function (bytes) {
return (bytes / 1024 / 1024).toFixed(2) + ' MB';
};
/** * 封装 print 方法输出内存占用信息 */
const print = function() {
const memoryUsage = process.memoryUsage();
    console.log(JSON.stringify({
    rss: format(memoryUsage.rss),
    heapTotal: format(memoryUsage.heapTotal),
    heapUsed: format(memoryUsage.heapUsed),
    external: format(memoryUsage.external),
    }));
}


5
function Quantity(num) { 
    if (num) {       
    return new Array(num * 1024 * 1024);
}
    return num;
}
function Fruit(name, quantity) { 
  this.name = name;
  this.quantity = new Quantity(quantity);
}
let apple = new Fruit('apple');
print();
let banana = new Fruit('banana', 20);
banana = null;
global.gc();
print();</syntaxhighlight>}}


6
{{shc_out|<syntaxhighlight lang="bash">
node --expose-gc test.js</syntaxhighlight>|<pre>{"rss":"28.03 MB","heapTotal":"6.83 MB","heapUsed":"4.23 MB","external":"0.01 MB"}
{"rss":"188.54 MB","heapTotal":"9.33 MB","heapUsed":"3.99 MB","external":"0.01 MB"}</pre>|$}}
{{unknown}}


7
对 gc 函数进行安全封装:
|<code>function</code> <code>forceGC()</code>
<syntaxhighlight lang="javascript">
 
function forceGC() {
<code> if</code> <code>(global.gc) {</code>
  if (global.gc){
 
    global.gc();
<code>  global.gc();</code>
  } else {
 
    console.warn('No GC hook....');
<code> } else</code> <code>{</code>
  }
 
}
<code>  console.warn('No GC hook! Start your program as `node --expose-gc file.js`.');</code>
 
<code> }</code>
 
<code>}</code>
|}


=====高效使用内存=====
=====高效使用内存=====
第342行: 第351行:
| Cell区、属性Cell区、Map区 || 示例 || 存放Cell、属性Cell和Map,每个区域都是存放相同大小的元素,结构简单
| Cell区、属性Cell区、Map区 || 示例 || 存放Cell、属性Cell和Map,每个区域都是存放相同大小的元素,结构简单
|}
|}


=== GC 回收类型 ===
=== GC 回收类型 ===