Node.js/内存:修订间差异
来自康健生活
| 第266行: | 第266行: | ||
=== --expose-gc === | === --expose-gc === | ||
强制回收垃圾 | 强制回收垃圾 | ||
{{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), | |||
})); | |||
} | |||
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}} | |||
对 gc 函数进行安全封装: | |||
<syntaxhighlight lang="javascript"> | |||
function forceGC() { | |||
if (global.gc){ | |||
global.gc(); | |||
} else { | |||
console.warn('No GC hook....'); | |||
} | |||
} | |||
=====高效使用内存===== | =====高效使用内存===== | ||
| 第342行: | 第351行: | ||
| Cell区、属性Cell区、Map区 || 示例 || 存放Cell、属性Cell和Map,每个区域都是存放相同大小的元素,结构简单 | | Cell区、属性Cell区、Map区 || 示例 || 存放Cell、属性Cell和Map,每个区域都是存放相同大小的元素,结构简单 | ||
|} | |} | ||
=== GC 回收类型 === | === GC 回收类型 === | ||