javascript – 如何检测v8堆使用率接近于Node.js中的限制

前端之家收集整理的这篇文章主要介绍了javascript – 如何检测v8堆使用率接近于Node.js中的限制前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
现在我使用:
const v8 = require('v8');

let heap = v8.getHeapStatistics();
let usage = 100 / heap.heap_size_limit * heap.used_heap_size;

if (usage > 90) {
    console.log(`V8 heap usage close to the limit (${usage.toFixed()}%)`);
} else if (usage > 95) {
    console.log(`V8 heap usage very close to the limit (${usage.toFixed()}%)`);
}

解决方案无法正常工作.

当我尝试这个命令时:node –max-old-space-size = 100 index.js
当我的脚本计算~56%时,我的进程无法分配内存

getHeapStatistics().heap_size_limit is 178 MB
getHeapStatistics().used_heap_size is ~95 MB

当我们出现内存错误时,如何更准确地检测情况?

解决方法

v8堆实际上被拆分为区域或空格:new_space,old_space,code_space,map_space和large_object_space.前两个大致对应于托儿所和终身对象堆,但理论上对象可以位于五个空间中的任何一个中.

更准确的衡量方法是使用old_space的space_size和space_used_size.

var space = v8.getHeapSpaceStatistics();
var old_space_total = space[1].space_size;
var old_space_used = space[1].space_used_size;
var usage = 100 / old_space_total * old_space_used;
if (usage > 90) {
    console.log(`V8 heap usage close to the limit (${usage.toFixed()}%)`);
} else if (usage > 95) {
    console.log(`V8 heap usage very close to the limit (${usage.toFixed()}%)`);
}

内存耗尽前的统计信息:

#node --max_old_space_size=200 heap.js
...
{ total_heap_size: 243306496,total_heap_size_executable: 5242880,total_physical_size: 243306496,total_available_size: 19149632,used_heap_size: 215801616,heap_size_limit: 243269632 }
[ { space_name: 'new_space',space_size: 33554432,space_used_size: 16464888,space_available_size: 41992,physical_space_size: 33554432 },{ space_name: 'old_space',space_size: 205475840,space_used_size: 197215464,space_available_size: 18462512,physical_space_size: 205475840 },{ space_name: 'code_space',space_size: 2097152,space_used_size: 680416,space_available_size: 617024,physical_space_size: 2097152 },{ space_name: 'map_space',space_size: 2179072,space_used_size: 1452528,space_available_size: 18800,physical_space_size: 2179072 },{ space_name: 'large_object_space',space_size: 0,space_used_size: 0,space_available_size: 0,physical_space_size: 0 } ]
V8 heap usage close to the limit (96%)
...
FATAL ERROR: CALL_AND_RETRY_LAST Allocation Failed - JavaScript heap out of memory

我们可以看到,total_heap_size:243306496实际上是新空间(33554432),旧空间(205475840),代码(2097152),地图(2179072),大对象(0)的总和.

正如你所看到的,所有其他空间都是健康的,而旧空间已经接近疲惫,实际的疲惫来自那里.

希望这可以帮助.

猜你在找的JavaScript相关文章